ActiveMQ消息队列
原创
©著作权归作者所有:来自51CTO博客作者蹊源的奇思妙想的原创作品,请联系作者获取转载授权,否则将追究法律责任
ActiveMQ消息队列
消息队列的作用
为什么会需要消息队列(MQ)?
主要原因是由于在高并发环境下,由于来不及同步处理,请求往往会发生堵塞,比如说:
大量的insert,update之类的请求同时到达MySQL,直接导致无数的行锁表锁,甚至最后请求会堆积过多,从而触发too many connections错误。通过使用消息队列,我们可以异步处理请求,从而缓解系统的压力。
消息队列的功能:
方式一:结合SpringBoot使用内嵌的ActiveMQ
第一步添加创建消息的方法
@Bean
public Queue productActiveMQQueue(){
return new ActiveMQQueue("jim.queue.product");
}
第二步创建消息生产者
- 可以在Controller层(也可以直接封装在Service)
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue productActiveMQQueue;
public void sendMessage(Object message) {
this.jmsMessagingTemplate.convertAndSend(this.productActiveMQQueue,"发送新消息");
}
第三步:创建消息监听者(消费者)
@JmsListener(destination = "jim.queue.product")
public void receiveQueue(String text) {
System.out.println("Consumer,productId:"+text);
}
方式二:ActiveMQ可以单独(设置分布式)安装在服务器中,通过远程调用从而获取服务。
第一步:在启动类Application.java中添加创建消息的方法
private static final String BROKER_URL="failover:(tcp://192.168.10.222:61616,tcp://192.168.10.222:61617,tcp://192.168.10.222:61618,tcp://192.168.10.222:61619)";
@Bean
public Queue productActiveMQQueue(){
return new ActiveMQQueue("jim.queue.product");
}
//创建JMS工厂
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerQueue() {
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
bean.setConnectionFactory(new ActiveMQConnectionFactory(BROKER_URL));
return bean;
}
//创建JMS模板
@Bean
public JmsMessagingTemplate jmsMessagingTemplate(){
return new JmsMessagingTemplate(new ActiveMQConnectionFactory(BROKER_URL));
}
第二步 创建消息生产者
- 在Controller层(或者在service 直接进行封装) 映射一个方法 用来生产消息队列
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue productActiveMQQueue;
@RequestMapping("/send")
public void send()
{
this.jmsMessagingTemplate.convertAndSend(this.queue,"新发送的信息");
}
第三步 创建消息消费者
@JmsListener(destination = "jim.queue.product",containerFactory = "jmsListenerContainerQueue")
public void receiveQueue(String text) {
System.out.println("Consumer,productId:"+text);
}
Kafka与ActiveMQ的对比
- Kafka 是LinkedIn 开发的一个高性能、分布式的消息系统,广泛用于日志收集、流式数据处理、在线和离线消息分发等场景。(虽然不是作为传统的MQ来设计,在大部分情况,Kafaka也可以代替原先ActiveMQ 等传统的消息系统)。
- Kafka有一定几率产生重复消息、消息乱序,配置起来依托zookeeper保持其高可用,搭建成本比较高。