本文介绍springboot如何整合activemq实现消息的发送与接收。
前言
一个项目是由好多子系统组合而成的,为了减少各系统之间的耦合性,便于整体项目的扩展,各系统之间可采用消息传递的方式进行通信,这时候就会用到消息队列。例如业务逻辑系统与日志收集系统之间的通信,业务逻辑系统将日志信息发送到消息队列中,然后日志收集系统从队列中取出消息进行日志的保存。同时,消息队列也可用于对那些实时性要求不高的异步处理场景。
准备工作
Apache activemq下载地址:http://activemq.apache.org/download.html
下载apache-activemq-5.15.0-bin.zip后解压即可。
启动命令:./bin/activemq start
运行起来后, 可以通过 ip:8161 来查看是否成功。
开发
maven依赖
<!-- 整合activemq控件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
application.properties增加配置
#activemq config spring.activemq.user=admin spring.activemq.password=admin spring.activemq.broker-url=tcp://127.0.0.1:61616
ActiveMQConfig注入
@Configuration @EnableJms public class ActiveMQConfig { @Bean public Queue queue() { return new ActiveMQQueue("parkcar.msg.queue") ; } }
注解声明:
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
注解@EnableJms
设置在@Configuration
类上,用来声明对 JMS 注解的支持。
parkcar.msg.queue是定义一个队列,数据的传递和接受都是通过此队列。如果多个项目共用一个activemq,那需要在各个项目中定义各自的队列,避免A项目生产的消息被B项目消费。
消息生产者
下面定义一个接口和一个接口实现类:
public interface IMessageProducerService { //发送日志消息到消息队列中 public void sendSystemErrorMessage(String type); }
@Service public class MessageProducerServiceImpl implements IMessageProducerService { @Resource private JmsMessagingTemplate jmsMessagingTemplate; @Resource private Queue queue; @Override public void sendSystemErrorMessage(String type) { Map<String,String> map = new HashMap<>(); map.put("type", type); this.jmsMessagingTemplate.convertAndSend(this.queue, map); } }
注:jmsMessagingTemplate.convertAndSend代表将消息放到队列中。
消息消费者
@Service public class MessageConsumerService { private static Logger log = Logger.getLogger(MessageConsumerService.class); @JmsListener(destination="parkcar.msg.queue") public void receiveMessage(Map<String,String> resultMap) { // 进行消息接收处理 String type = resultMap.get("type"); } }
注:@JmsListener(destination="parkcar.msg.queue")用于声明从哪个队列中接收消息。receiveMessage方法用于消息的接受和逻辑处理
具体使用
假如UserCarController类中需要调用消息队列,那就需要将消息生产者注入,然后利用生产者的方法将消息放到队列中,再由消费者进行消费。
@Controller
@EnableAutoConfiguration
public class UserCarController {
private static Logger log = Logger.getLogger(UserCarController.class);
@Autowired
private IMessageProducerService messageProducer;
@RequestMapping(value="/addOrUpdateUserCarInfo")
@ResponseBody
public Map<String,Object> addUserCarInfo(String tel){
messageProducer.sendSystemErrorMessage("saveAxbRecord");
}
}
以上为springboot整合activemq的全部流程。欢迎在评论区留言,我会尽快回复~~~
最后,打波广告。微信搜索公众号"购即省",淘宝购物领券,购物即省钱。