引入pom.xml
<!--Spring Boot项目-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<!--spring-boot的activeMQ依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
</dependencies>
activeMq.properties
#activeMQ部署地址
spring.activemq.broker-url=tcp://192.168.159.128:61616
#activeMQ访问用户名
spring.activemq.user=admin
#activeMQ访问密码
spring.activemq.password=admin
#监听topic的消息
spring.jms.pub-sub-domain=true
在公共项目中引入 ActiveMqConfig(如果不交给spring管理,每次都新建一个队列,这样做 不好 )
@Configuration
public class ActiveMqConfig {
@Bean
public Destination generateOrderQueue(){
return new ActiveMQQueue("generateOrderQueue");
}
@Bean
public Destination generateOrderTopic(){
return new ActiveMQTopic("generateOrderTopic");
}
/**
* 用于监听Topic模型消息的容器bean
*/
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory jmsConnectionFactory) {
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
//是否使用订阅和发布的模型监听器,默认为false,也就是说默认使用的是点对点的模型监听器
bean.setPubSubDomain(true);
bean.setConnectionFactory(jmsConnectionFactory);
return bean;
}
/**
* 用于监听Queue模型消息的容器bean
*/
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory jmsConnectionFactory) {
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
bean.setConnectionFactory(jmsConnectionFactory);
return bean;
}
}
生产者 组件
@Component
public class CreateOrderProduct {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Destination generateOrderQueue;//队列
@Autowired
private Destination generateOrderTopic;//主题/订阅
/**
* 发送生成订单消息
*/
public void sendMessage(String content){
//发送消息
jmsTemplate.convertAndSend(generateOrderQueue,content);
jmsTemplate.convertAndSend(generateOrderTopic,content);
}
}
使用时直接将其注入,然后调用方法即可
@Autowired
private CreateOrderProduct createOrderProduct;
_____________________________________________________________________________________________________
消费者: 同时监听queue和topic进行消费,将要执行的方法在里面调用即可
@Component
public class GenerateOrderConsumer {
@Autowired
IOrderInfoService orderInfoService;
/**
* 消息监听方法
*/
@JmsListener(destination = "generateOrderQueue",containerFactory = "jmsListenerContainerQueue")
public void listenerMassageQueue(Message message) throws JMSException {
TextMessage textMessage = (TextMessage) message;
OrderVo orderVo = JSON.parseObject(textMessage.getText(), OrderVo.class);
orderInfoService.createOrder(orderVo);
System.out.println(textMessage);
}
/**
* 消息监听方法
*/
@JmsListener(destination = "generateOrderTopic",containerFactory = "jmsListenerContainerTopic")
public void listenerMassageTopic(Message message){
TextMessage textMessage = (TextMessage) message;
System.out.println(textMessage);
}
}