SpringBoot如何集成ActiveMQ
1.在pom.xml文件中加入
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2. yml文件中添加
port: 8080
context-path: /pro
spring:
activemq:
user: admin
password: admin
broker-url: tcp://192.168.10.79:61616
pool:
enabled: true
max-connections: 10
topicName: publish.topic
3.新增配置ActiveMQConfig
/**
* @author: elvin
*/
@Configuration
public class ActiveMQConfig {
@Value("${queueName}")
private String queueName;
@Value("${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.PublishController消息发送方
/**
* @author: elvin
*/
@RestController
@RequestMapping("/publish")
public class PublishController {
@Autowired
private JmsMessagingTemplate jms;
@Autowired
private Queue queue;
@Autowired
private Topic topic;
@RequestMapping("/queue")
public String queue(){
for (int i = 0; i < 10 ; i++){
jms.convertAndSend(queue, "queue"+i);
}
return "queue 发送成功";
}
@JmsListener(destination = "out.queue")
public void consumerMsg(String msg){
System.out.println(msg);
}
@RequestMapping("/topic")
public String topic(){
for (int i = 0; i < 10 ; i++){
jms.convertAndSend(topic, "topic"+i);
}
return "topic 发送成功";
}
}