原创: 小柒2012
前言
在实际生产环境中中,通常生产者和消费者会是两个独立的应用,这样才能通过消息队列实现了服务解耦和广播。因为此项目仅是一个案例,为了方便期间,生产和消费定义在了同一个项目中。
安装说明
参考:Docker学习之搭建ActiveMQ消息服务
基础配置
pom.xml 添加依赖:
org.springframework.boot spring-boot-starter-activemq
application.properties 基础配置:
# activemq 基础配置#spring.activemq.broker-url=tcp://47.94.232.109:61616# 生产环境设置密码#spring.activemq.user=admin#spring.activemq.password=123456#spring.activemq.in-memory=true#spring.activemq.pool.enabled=false
项目集成
定义生产者:
import javax.jms.Destination;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jms.core.JmsMessagingTemplate;import org.springframework.stereotype.Component;@Componentpublic class ActiveMQSender { @Autowired private JmsMessagingTemplate jmsTemplate; /* * 发送消息,destination是发送到的队列,message是待发送的消息 */ public void sendChannelMess(Destination destination, final String message){ jmsTemplate.convertAndSend(destination, message); }}
定义消费者:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jms.annotation.JmsListener;import org.springframework.stereotype.Service;import com.itstyle.seckill.common.entity.Result;import com.itstyle.seckill.common.enums.SeckillStatEnum;import com.itstyle.seckill.common.redis.RedisUtil;import com.itstyle.seckill.common.webSocket.WebSocketServer;import com.itstyle.seckill.service.ISeckillService;@Servicepublic class ActiveMQConsumer { @Autowired private ISeckillService seckillService; @Autowired private RedisUtil redisUtil; // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息 @JmsListener(destination = "seckill.queue") public void receiveQueue(String message) { //收到通道的消息之后执行秒杀操作(超卖) String[] array = message.split(";"); Result result = seckillService.startSeckilDBPCC_TWO(Long.parseLong(array[0]), Long.parseLong(array[1])); if(result.equals(Result.ok(SeckillStatEnum.SUCCESS))){ WebSocketServer.sendInfo(array[0].toString(), "秒杀成功");//推送给前台 }else{ WebSocketServer.sendInfo(array[0].toString(), "秒杀失败");//推送给前台 redisUtil.cacheValue(array[0], "ok");//秒杀结束 } }}
测试案例:
@ApiOperation(value="秒杀五(ActiveMQ分布式队列)