本篇介绍ActiveMQ Topics消息方式,直接码代码演示了:
application.properties配置加入:
#spring.jms.pub-sub-domain=false # Specify if the default destination type is topic.
spring.jms.pub-sub-domain=true
消息生产者
package com.spring.boot.jms.producter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import javax.jms.Destination;
/**
* Description: 消息生产者
* author: 慢慢来了
* date: 2017/3/24 14:07
*/
@Component
public class Producter {
@Autowired
private JmsMessagingTemplate jmsTemplate;
public void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination, message);
}
}
消息消费者,写了二个方法监听msg.topics.demo队列
package com.spring.boot.jms.consumer;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
/**
* Description:
* author: 慢慢来了
* date: 2017/3/24 17:31
*/
@Component
public class ConsumerTopics {
@JmsListener(destination = "msg.topics.demo")
public void processMessage(String content) {
System.out.println("topics a message :" + content);
}
@JmsListener(destination = "msg.topics.demo")
public void processMessage2(String content) {
System.out.println("topics a message 2 :" + content);
}
}
编写单元测试
package com.spring.boot.jms;
import com.spring.boot.jms.producter.Producter;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.jms.Destination;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpirngBootJmsApplicationTests {
@Autowired
private Producter producter;
@Test
public void contextLoads() {
Destination p2pMsg = new ActiveMQQueue("msg.p2p.queue");
producter.sendMessage(p2pMsg , "hello , this is jms msg");
}
@Test
public void topics(){
Destination topics = new ActiveMQTopic("msg.topics.demo");
producter.sendMessage(topics , "hello , this topics msg");
}
}
结果如下: