jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-artemis</artifactId> </dependency>
点对点Queue
//生产者
@Autowired
private JmsTemplate jmsTemplate;
@Scheduled(cron="0/5 * * * * ? ")// 使用定时任务,每两秒向mq中发送一个消息
public void sendMsg(){
Map<String, String> ptpMap = new HashMap<>();
ptpMap.put("hello", "activeMQ");
jmsTemplate.convertAndSend("666", ptpMap);
}
//消费者
@JmsListener(destination = "666")// 通过JmsListerner实时获取mq中的消息
public void readMsg(Map map) {
System.out.println("currentTimeMillis" + System.currentTimeMillis() + " = [" + map.toString() + "]");
}
发布订阅Topic
spring.jms.pub-sub-domain=true #开启topic 原默认queue模式,二者不可得兼
//生产者
@Scheduled(cron="0/10 * * * * ?")// 使用定时任务,每两秒向mq中发送一个消息
public void sendMsg5(){
System.out.println("112start");
jmsTemplate.convertAndSend("112","666");
}
//消费者
@JmsListener(destination = "112")
public void recieve112A(String message) {
System.out.println("服务订阅112Atopic接收消息: " + message);
}
@JmsListener(destination = "112")
public void recieve112B(String message) {
System.out.println("服务订阅112Btopic接收消息: " + message);
}
小结:
spring.jms.pub-sub-domain=false artemis 自动走queue,只能发布点对点模式,多个订阅者轮流消费不同消息,
spring.jms.pub-sub-domain=true 阿尔忒弥斯自动走topic,可以进行订阅发布模式,多个订阅者同一时间消费同一消息,实现解耦。