SpringBoot +docker 集成 ActiveMQ

ActiveMQ 介绍

MQ (MessageQueue)中文称消息队列,用于消息接收和转发的容器,可用于消息推送。Active MQ 是一个Java的开源消息系统。很好的支持了 JMS 规范。

ActiveMQ 安装

这里使用的Docker安装 地址:docker安装activemq

ActiveMQ 集成

在pom.xml中引入依赖

<!--ActiveMQ-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

在application.properties配置

###ActiveMQ 配置
spring.activemq.broker-url = tcp://localhost:61616
spring.activemq.in-memory = true
spring.activemq.pool.enable = false
spring.activemq.package.trust-all = true

ActiveMQ 使用

我们都知道QQ空间有一个发说说的功能,这里有很多的用户同一时刻会发送大量的说说,这样我们如果采用同步的方式,每一个用户都占用一条线程,那么会导致系统性能大幅度降低。这样就需要我们的ActiveMQ来进行异步消费抵抗高使用量的冲击。

设计一个可以实现异步消费的生产者和消费者模型
消费者

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;


/**
 * 描述:消费者
 * @author wangyu
 * @date 2019/5/16
 */
@Component
public class Consumer {
    @JmsListener(destination = "activemq.queue")
    
    public void receiveQueue(String text) {
        System.out.println("信息接受***  "+text+" ***成功");
    }
}

@JmsListener(destination = “activemq.queue”) 监听队列信息
destination = “activemq.queue” :监听的队列名

生产者

import javax.jms.Destination;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 描述:生产者
 * @author wangyu
 * @date 2019/5/15
 */

@Service
public class Producer {
    @Resource
    private JmsTemplate jmsTemplate ;

    public void sendMessage(Destination destination, final String message) {
        jmsTemplate.convertAndSend(destination,message);
    }
}

生产者消费者模型测试

/**
 * 描述:ActiveMQ 测试
*/
@Test
public void testActiveMQ() {
   Destination destination = 
      new ActiveMQQueue("activemq.queue") ;
   producer.sendMessage(destination,"ActiveMQ测试消息");
}

打印出如下结果:

信息接受*** ActiveMQ测试消息 ***成功
以QQ空间的数据库简单的操作测试ActiveMQ的使用

根据我们对插入数据的操作和生产者消费者的模型结合,就是将我们的设置说说内容的操作放到生产者中,而将保存的插入数据库的操作放到消费者中。就可以达到异步插入的目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图图是只猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值