我使用的SpringBoot的版本为 2.0.3.RELEASE
首先pom.xml文件中加入ActiveMQ的相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
application.properties文件中加入ActiveMQ的相关配置:
spring.activemq.broker-url=tcp://127.0.0.1:61616
#账号
spring.activemq.user=admin
# 密码
spring.activemq.password=admin
# 默认代理URL是否应该在内存中。如果指定了显式代理,则忽略此值。
spring.activemq.in-memory=true
#true表示使用连接池
spring.activemq.pool.enabled=true
#连接池最大连接数
spring.activemq.pool.max-connections=5
#空闲的连接过期时间,默认为30秒
spring.activemq.pool.idle-timeout=30s
# 等待消息发送响应的时间。设置为0等待永远。
#spring.activemq.send-timeout=0
#强制的连接过期时间,与idleTimeout的区别在于:idleTimeout是在连接空闲一段时间失效,而expiryTimeout不管当前连接的情况,只要达到指定时间就失效。默认为0,never
#spring.activemq.pool.expiry-timeout=0
#默认情况下activemq提供的是queue模式,若要使用topic模式需要将以下属性设置为true
#spring.jms.pub-sub-domain=true
在Application启动类中构建ConnectionFactory并初始化JmsMessagingTemplate:
@Value("${spring.activemq.broker-url}")
private String amq_url;
@Value("${spring.activemq.user}")
private String amq_user;
@Value("${spring.activemq.password}")
private String amq_password;
@Bean
public ConnectionFactory connectionFactory(){
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL(amq_url);
connectionFactory.setUserName(amq_user);
connectionFactory.setPassword(amq_password);
return connectionFactory;
}
@Bean
public JmsMessagingTemplate jmsMessageTemplate(){
return new JmsMessagingTemplate(connectionFactory());
}
创建一个类初始化queue和topic,由于一个项目中queue和topic只能同时使用其中的一种,需要将另一种注释掉
@Configuration
@EnableJms
public class AMQConfig {
//创建queue实例(引号内即为queue的发布主题)
@Bean
public Queue queue() {
return new ActiveMQQueue("active.queue");
}
//创建topic实例(引号内即为topic的发布主题)
/*@Bean
public Topic topic() {
return new ActiveMQTopic("active_topic");
}*/
}
创建一个类将服务发布到主题上(生产者),同样,Queue和Topic只能创建一种方式
@RestController
@Component
@EnableScheduling
public class ProducerTest{
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@RequestMapping("/sendQueue")
public void sendmsg(String msg) {
// 指定消息发送的目的地及内容
this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
}
/* @Autowired
private Topic topic;
@RequestMapping("/sendTopic")
public void send(String msg) {
this.jmsMessagingTemplate.convertAndSend(this.topic, msg);
}*/
}
上述生产者的消费者类:
@Component
public class QueueConsumer {
@JmsListener(destination ="active.queue")
public void receiveQueue(String msg) {
}
}