SpringBoot整合Rabbitmq

1.pom.xml中引入rabbitmq jar包

XML 复制代码
<!-- mq启动器 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.application.yaml中添加rabbitmq配置

XML 复制代码
spring
  rabbitmq:
    publisher-confirm-type: correlated
    host: 192.168.1.141
    port: 30001
    username: haha
    password: 1234
    virtual-host: /HAHA
    template:
      retry:
        # 开始重试
        enabled: true
        # 第一次与第二次投递尝试的时间间隔10秒
        initial-interval: 10000ms
        # 尝试的最大时间间隔不超过30秒
        max-interval: 30000ms
        # 上一次尝试时间间隔的乘数2*10000ms
        multiplier: 2
      mandatory: true
    publisher-returns: true
    # 不使用自动确认 改成手动确认
    listener:
      type: simple
      simple:
        #采用手动应答
        acknowledge-mode: manual
		
haha:
  mq:
    # 日志 交换机
    logExchange: haha.shop.log.exchange
    # 日志 成功队列
    logQueue: haha.shop.log.queue
    # 日志 路由键
    logRouteKey: haha.shop.log.route-key
    # 库存明细 交换机
    stockInfoExchange: haha.shop.stock.exchange
    # 库存明细 成功队列
    stockInfoQueue: haha.shop.stock.queue
    # 库存明细 路由键
    stockInfoRouteKey: haha.shop.stock.route-key

3.发送rabbitmq消息

java 复制代码
@Resource
private RabbitTemplate rabbitTemplate;

    @Value("${haha.mq.stockInfoExchange}")
    private String exchange;

    @Value("${haha.mq.stockInfoRouteKey}")
    private String routingKey;

    @Override
    public boolean sendStockInfoMQ(ProductStockInfoReq productStockInfoReq) {
        if (productStockInfoReq != null && productStockInfoReq.getStock() != null) {
            rabbitTemplate.convertAndSend(exchange, routingKey, JSONUtil.toJsonStr(productStockInfoReq));
            return true;
        }
        return false;
    }
	

4.接收rabbitmq消息

java 复制代码
@Slf4j
@Service("stockInfoMqConsumer")
public class StockInfoMqConsumer {
    @Autowired
    private IProductStockInfoService productStockInfoService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "${haha.mq.stockInfoQueue}", durable = "true"),
            exchange = @Exchange(name = "${haha.mq.stockInfoExchange}", type = ExchangeTypes.TOPIC),
            key = {"*.shop.stock.route-key"}
    ))
    public void logRecordConsumer(Message message, String content, Channel channel) {
        log.info("店铺库存日志明细消费,消息内容:{}" , content);
        try {
            if (StrUtil.isNotEmpty(content)) {
                ProductStockInfoReq productStockInfoReq = JSONUtil.toBean(content, ProductStockInfoReq.class);
                if (productStockInfoReq.getStoreId() == null) {
                    Integer storeId = productStockInfoService.getStoreIdByStoreId(productStockInfoReq.getStoreId());
                    if (storeId != null) {
                        productStockInfoReq.setStoreId(storeId);
                        // 保存结果数据
                        ProductStockInfo productStockInfo = new ProductStockInfo();
                        BeanUtil.copyProperties(productStockInfoReq, productStockInfo);
                        // 设置时间
                        productStockInfo.setCreateTime(DateUtil.parse(productStockInfoReq.getCreateTimeStr(), DatePattern.NORM_DATETIME_FORMAT));
                        productStockInfo.setBillType(productStockInfoReq.getRemark());
                        boolean save = productStockInfoService.save(productStockInfo);
                        log.info("店铺库存日志明细消费,保存结果:{}" , save);
                        if (save) {
                            //采用手动ack,一条条的消费
                            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                        }
                    } else {
                        log.error("店铺库存日志明细消费,未查找到店铺:{}" , storeId);
                    }
                } else {
                    // 保存结果数据
                    ProductStockInfo productStockInfo = new ProductStockInfo();
                    BeanUtil.copyProperties(productStockInfoReq, productStockInfo);
                    // 设置时间
                    if(StrUtil.isNotEmpty(productStockInfoReq.getCreateTimeStr())){
                        productStockInfo.setCreateTime(DateUtil.parse(productStockInfoReq.getCreateTimeStr(), DatePattern.NORM_DATETIME_FORMAT));
                    }
                    productStockInfo.setBillType(productStockInfoReq.getRemark());
                    boolean save = productStockInfoService.save(productStockInfo);
                    log.info("店铺库存日志明细消费,保存结果:{}" , save);
                    if (save) {
                        //采用手动ack,一条条的消费
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    }
                }
            } else {
                //采用手动ack,一条条的消费
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
相关推荐
攒了一袋星辰1 分钟前
今日指数项目项目集成RabbitMQ与CaffienCatch
java·分布式·rabbitmq
ZhongruiRao3 分钟前
Springboot+PostgreSQL+MybatisPlus存储JSON或List、数组(Array)数据
spring boot·postgresql·json
IT学长编程15 分钟前
计算机毕业设计 Java酷听音乐系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·音乐系统·计算机毕业设计选题
IT学长编程33 分钟前
计算机毕业设计 基于协同过滤算法的个性化音乐推荐系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·毕业论文·协同过滤算法·计算机毕业设计选题·个性化音乐推荐系统
华农第一蒟蒻1 小时前
Java中JWT(JSON Web Token)的运用
java·前端·spring boot·json·token
计算机学姐1 小时前
基于SpringBoot+Vue的高校运动会管理系统
java·vue.js·spring boot·后端·mysql·intellij-idea·mybatis
老华带你飞1 小时前
公寓管理系统|SprinBoot+vue夕阳红公寓管理系统(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·课程设计
程序员陆通2 小时前
Spring Boot RESTful API开发教程
spring boot·后端·restful
我是浮夸3 小时前
MyBatisPlus——学习笔记
java·spring boot·mybatis
杨荧3 小时前
【JAVA开源】基于Vue和SpringBoot的水果购物网站
java·开发语言·vue.js·spring boot·spring cloud·开源