1.添加pom文件
<!-- ActiveMQ的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2.添加配置类
@Configuration
public class ActiveMQConfig {
@Bean
public Queue queue() {
return new ActiveMQQueue("test.queue");
}
@Bean
public Topic topic() {
return new ActiveMQTopic("test.topic");
}
3。yml文件中配置:
#activemq 配置
# MQ所在的服务器的地址
spring.activemq.broker-url=tcp://127.0.0.1:61616
# 是否使用内置的MQ, true 使用; false 不使用
spring.activemq.in-memory=false
# 是否在回滚回滚消息之前停止消息传递。这意味着当启用此命令时,消息顺序不会被保留。
spring.activemq.non-blocking-redelivery=false
# 用户名
spring.activemq.password=admin
# 密码
spring.activemq.user=admin
4.配置生产者:
@RestController
@RequestMapping(value = "activemq")
public class QueueProducer {
@Autowired
private JmsMessagingTemplate jms;
@Autowired
private Queue queue;
/**
* @Author zhangxiaofeng
* @Description //TODO activemq 生产者
* @Date 2019/6/7 10:26
* @Param []
* @return void
**/
@RequestMapping("/send")
public void send(){
try {
// --------jms5中消息类型-------
/*TextMessage 主体包含字符串
BytesMessage 主体包含连续字节流
MapMessage 主体包含键值对
StreamMessage 主体包含流
ObjectMessage 主体包含对象*/
ActiveMQMapMessage message= new ActiveMQMapMessage();
//发送的消息为对象类型
//传输对象时不序列化:Only objectified primitive objects, String, Map and List types are allowed
//message.setObject("active", SerializeUtil.serialize(new Active(1,"zxf",111)));
//发送的消息为字符串类型
message.setString("info", "敲bug");
//发送消息,并绑定队列名称
jms.convertAndSend(queue,message);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
5.配置监听(消费者)
@Component
public class QueueConsumer {
/**
* @Author zhangxiaofeng
* @Description //TODO
* @Date 2019/5/23 18:33
* @Param [message]
* @return
**/
@JmsListener(destination = "activemqQueue")
public void receiveQueue(Message message){
try {
MapMessage mapMessage =(MapMessage) message;
//接受字符串类型
String info = mapMessage.getString("info");
System.out.println(info);
//接受对象类型
/*byte[] actives =(byte[]) mapMessage.getObject("active");
Active active = (Active) SerializeUtil.deserialize(actives);
System.out.println(active);
System.out.println("ID>>>"+active.getAcId()+" NAME>>>"+active.getAcName()+" AGE>>>"+active.getAcAge());*/
} catch (JMSException e) {
e.printStackTrace();
}
}
}