開發與維運

SpringBoot怎樣整合ActiveMQ?

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《SpringBoot實戰教程》,主講人楊紅豔,點擊查看視頻內容

SpringBoot整合ActiveMQ

ActiveMQ是符合JMS規範的消息管理者。
如何使用呢?
在工程中添加依賴:

<!-- 整合ActiveMQ的依賴 -->
       <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-activemq</artifactId>  
       </dependency> 

全局配置文件進行配置

spring.activemq.broker-url=tcp://192.168.25.129:61616
spring.activemq.in-memory=true
spring.activemq.user=admin
spring.activemq.password=admin
#如果此處設置為true,需要加如下面的依賴包,否則會自動配置失敗,JmsMessagingTemplate
spring.activemq.pool.enabled=false

依賴如下:

<dependency>  
                <groupId>org.apache.activemq</groupId>  
                <artifactId>activemq-pool</artifactId> 
     </dependency> 

如何實現消息的發送和消息的接收?
新建包:com.qianfeng.activemq:

@Component
public class Producer {

   @Autowired
    private JmsMessagingTemplate jmsTemplate;


    //發送消息
    public void sendMessage(Destination des, String message) {
        jmsTemplate.convertAndSend(des, message);
     }
}


@Component
public class Consumer {

    @JmsListener(destination="myqueues")
    public void receiveMsg(String text) {
        System.out.println(text+"......");
    }
}

新建包com.qianfeng.controller:

@Controller
public class TestController {

    @Autowired
    private Producer producer;


    @RequestMapping("/activemq")
    @ResponseBody
    public String tests() {
        //點對點消息
        Destination des = new ActiveMQQueue("myqueues");
        for(int i = 1; i <= 3; i++) {
            producer.sendMessage(des, "hello");
        }
        return "ok";
    }
}

在啟動類中添加所有需要掃描的包:

@SpringBootApplication(scanBasePackages="com.qianfeng")

執行結果:
image.png
image.png

配套視頻

Leave a Reply

Your email address will not be published. Required fields are marked *