activeMQ整合springboot簡單入門

1.下載activeMQ,傳送門:http://activemq.apache.org/activemq-5158-release.html

2.解壓到bin目錄下,我是64位,進win64,雙擊activemq.bat,運行。也可以進到win64目錄下運行activemq start運行,效果一樣。之前看別人的文章有的說在這個下面直接運行activemq.bat,那樣應該是會閃退,可能是版本不同了吧,現在多了兩個文件夾,找到對應計算機位數,進到子目錄夾下,運行就不閃退了。(我的是這樣)

瀏覽器輸入http://127.0.0.1:8161/,這個樣子也就是運行成功了

3.創建一個springboot項目,基於idea這個教程很多,就不多說了。

4.pom加activemq依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>

5.寫一個controller類

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 基於隊列,點對點
     */
    @RequestMapping("sendMsg")
    public void sendMsg(){
        jmsMessagingTemplate.convertAndSend("my_msg","這就行了?");
    }

    @RequestMapping("/sendMap")
    public void sendMap() {
        Map map = new HashMap();
        map.put("name", "lucky");
        map.put("content", "幸運兒?");
        jmsMessagingTemplate.convertAndSend("my_map", map);
    }

    /**
     * 基於主題,發佈/訂閱
     */
    @RequestMapping("sendTopic")
    public void sendTopic(){
        for(int i = 0;i < 10;i++){
            jmsMessagingTemplate.convertAndSend("my_topic_1", "這是topic:" + i);
        }
    }

前兩個是基於隊列,點對點模式,後一個是基於主題,發佈/訂閱。

6.寫一個類來接受點對點模式消息

@Component
public class QueueConsumer {

    @JmsListener(destination = "my_msg")
    public void getMsg(String text){
        System.out.println(">>>>>>>>>>>>>>>>>>>msg:" +  text);
    }

    @JmsListener(destination = "my_map")
    public void readMap(Map map) {
        System.out.println(">>>>>>>>>>>>>>>>>>map:" + map);
    }
}

7.寫兩個類來接受發佈/訂閱模式消息

@Component
public class TopicConsumerA {

    // 使用JmsListener配置消費者監聽的隊列,其中text是接收到的消息
    @JmsListener(destination = "my_topic_1")
    public void receiveQueue(String text) {
        System.out.println("ConsumerA收到的消息爲:" + text);
    }
}



@Component
public class TopicConsumerB {
    @JmsListener(destination = "my_topic_1")
    public void receiveQueue(String text) {
        System.out.println("ConsumerB收到的消息爲:" + text);
    }
}

8.配置文件application.properties

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
spring.jms.pub-sub-domain=true

注意spring.jms.pub-sub-domain=true這個配置

這個地方設置爲true時只能用發佈/訂閱模式,設置爲false時候只能用點對點模式。也就是說,只能用一種模式,怎樣把兩種模式放在一起,還沒弄明白。

 

最後運行項目就行了。

這裏就是簡單介紹一個springboot簡單整合activemq一,性能啊,什麼些別的配置的東西,額,我也不太熟悉,看了很多大神的文章,表示感謝,留個記錄,方便自己學習,也是屬於剛剛學習的階段,要是有什麼不對的,歡迎指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章