1. pom.xml加入依赖
<!--ActiveMq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!--消息队列连接池-->
<dependency>
<groupId>org.messaginghub</groupId>
<artifactId>pooled-jms</artifactId>
</dependency>
2. application.yml加入配置
spring:
#activityMQ
activemq:
broker-url: tcp://127.0.0.1:61616
user: admin
password: admin
pool:
enabled: false
queueName: publish.queue
topicName: publish.topic
3. 创建ActiveMQConfig.java
@Configuration
public class ActiveMQConfig {
@Value("${spring.activemq.queueName}")
private String queueName;
@Value("${spring.activemq.topicName}")
private String topicName;
@Value("${spring.activemq.user}")
private String usrName;
@Value("${spring.activemq.password}")
private String password;
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
@Bean
public Queue queue(){
return new ActiveMQQueue(queueName);
}
@Bean
public Topic topic(){
return new ActiveMQTopic(topicName);
}
@Bean
public ActiveMQConnectionFactory connectionFactory() {
return new ActiveMQConnectionFactory(usrName, password, brokerUrl);
}
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory){
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
bean.setConnectionFactory(connectionFactory);
return bean;
}
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory){
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
//设置为发布订阅方式, 默认情况下使用的生产消费者方式
bean.setPubSubDomain(true);
bean.setConnectionFactory(connectionFactory);
return bean;
}
}
4. 创建QueueListener.java
@Component
public class QueueListener {
@JmsListener(destination = "publish.queue", containerFactory = "jmsListenerContainerQueue")
public void receive(String msg){
System.out.println(msg);
}
}
5. 创建TopicListener.java
@Component
public class TopicListener {
@JmsListener(destination = "publish.topic", containerFactory = "jmsListenerContainerTopic")
public void receive(String msg){
System.out.println(msg);
}
}
6. 启动类增加注解
@EnableJms//启动消息队列
6. 创建PublishController.java测试一下
@RestController
@RequestMapping("/mq")
public class PublishController {
@Autowired
private JmsMessagingTemplate jms;
@Autowired
private Queue queue;
@Autowired
private Topic topic;
/*发布消息(队列模式)*/
@RequestMapping("/sendQueue")
public String queue(){
jms.convertAndSend(queue,"队列消息");
return "queue 发送成功";
}
/*发布消息(主题模式)*/
@RequestMapping("/sendTopic")
public String topic(){
jms.convertAndSend(topic,"主题消息");
return "topic 发送成功";
}
}