SpringBoot配置ActiveMQ


1、添加依賴

<!-- activeMQ -->
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-activemq</artifactId>  
</dependency>
<!-- activeMQ的連接池 -->
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-pool</artifactId>
</dependency>

 

 

2、application.properties配置

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin spring.activemq.password=admin #queue和topic不能同時使用(我不會同時使用),使用topic的時候,把下面這行解除注釋 #spring.jms.pub-sub-domain=true spring.activemq.pool.enabled=false spring.activemq.pool.max-connections=50

 

 

3、生產者

import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProducerController {
    
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
 
    @Autowired
    private Queue queue;
 
    @Autowired
    private Topic topic;
 
    /*
     * 消息生產者
     */
    @RequestMapping("/sendQueueMsg")
    public void sendQueueMsg(String msg) {
        this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
    }
 
    @RequestMapping("/sendTopicMsg")
    public void sendTopicMsg(String msg) {
        // 指定消息發送的目的地及內容
        System.out.println("@@@@@@@@@@@@@@" + msg);
        this.jmsMessagingTemplate.convertAndSend(this.topic, msg);
    }
}

 

 

 

4、消費者

import org.springframework.jms.annotation.JmsListener; import org.springframework.web.bind.annotation.RestController; @RestController public class ConsumerController { /** * 監聽和讀取queue消息 * @param message */ @JmsListener(destination="active.queue") public void readActiveQueue(String message) { System.out.println("接受到:" + message); //TODO something
 } /** * 監聽和讀取topic消息 * @param message */ @JmsListener(destination="active.topic") public void readActiveTopic(String message) { System.out.println("接受到:" + message); //TODO something
 } }

 

 

 

5、發布/訂閱的主題名稱

import javax.jms.Queue; import javax.jms.Topic; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; @Configuration @EnableJms public class JmsConfig { private static final String QUEUE_NAME = "active.queue"; private static final String TOPIC_NAME = "active.topic"; @Bean public Queue queue(){ return new ActiveMQQueue(QUEUE_NAME); } @Bean public Topic topic(){ return new ActiveMQTopic(TOPIC_NAME); } }

 

 

 

測試

瀏覽器輸入:

http://localhost:8080/sendQueueMsg?msg=dddddd

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM