手动确认rabbitmq

配置文件

java 复制代码
package com.ynart.config;


import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitmqConfig {

    private static final String PRODUCT_EXCHANGE = "productExchange";

    @Bean
    public TopicExchange productExchange() {
        return new TopicExchange(PRODUCT_EXCHANGE);
    }

    @Bean
    public Queue sportsQueue() {
        return new Queue("sportsQueue");
    }

    @Bean
    public Binding sportsBinding(Queue sportsQueue, TopicExchange productExchange) {
        return BindingBuilder.bind(sportsQueue).to(productExchange).with("sports.*");
    }

    @Bean
    public Queue electronicsQueue() {
        return new Queue("electronicsQueue");
    }

    @Bean
    public Binding electronicsBinding(Queue electronicsQueue, TopicExchange productExchange) {
        return BindingBuilder.bind(electronicsQueue).to(productExchange).with("electronics.*");
    }

    /**
     * 创建消息监听容器
     * @param connectionFactory
     * @return
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); // 设置消息确认模式为手动确认
        return factory;
    }
}

使用

java 复制代码
package com.ynart.rabbitmq;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ynart.Dto.ArtDataEntity;
import com.ynart.exedata.domain.ArtData;
import com.ynart.exedata.service.IArtDataService;
import com.ynart.utils.AesUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@Component
public class RabbitmqService {

    private final RabbitTemplate rabbitTemplate;
    @Autowired
    private IArtDataService artDataService;
    @Autowired
    private AesUtils aesUtils;

    @Autowired
    public RabbitmqService(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendSportsOrder(String message) {
        rabbitTemplate.convertAndSend("productExchange", "sports.new", message);
    }

    public void sendElectronicsOrder(String message) {
        rabbitTemplate.convertAndSend("productExchange", "electronics.new", message);
    }

    @RabbitListener(queues = "sportsQueue")
    public void receiveSportsOrder(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {

            //TODO 数据梳理入库
            message = aesUtils.decryptAES(message);
            ObjectMapper objectMapper = new ObjectMapper();
            List<ArtDataEntity> list = objectMapper.readValue(message, new TypeReference<List<ArtDataEntity>>() {
            });
            String pattern = "yyyy-MM-dd HH:mm:ss";

            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
            //mq数据入库
            for (ArtDataEntity artDataEntity : list) {
                ArtData artData = new ArtData();
                artData.setId(null);
                artData.setJsonContent(artDataEntity.getJson_content());
                artData.setUrl(artDataEntity.getUrl());
                artData.setDataVersion(artDataEntity.getData_version());
                artData.setSign(artDataEntity.getSign());
                artData.setStatus(artDataEntity.getStatus().toString());
                artData.setCreatedBy(artDataEntity.getCreated_by());
                artData.setCreatedTime(dateFormat.parse(artDataEntity.getCreated_time()));
                artData.setUpdatedBy(artDataEntity.getUpdated_by());
                artData.setUpdatedTime(dateFormat.parse(artDataEntity.getUpdated_time()));
                artDataService.insertArtData(artData);

            }
            // 手动确认消息
            channel.basicAck(deliveryTag, false);

            //TODO 逻辑修改,不进行回调
//            sendElectronicsOrder(list.get(0).getCreated_by() + ":-art-:" + stringBuilder.toString());

        } catch (Exception e) {
            // 消费消息失败,不进行确认,消息重新回到队列中进行重试
            System.out.println("Failed to process sports order: " + message);
            //TODO 逻辑修改,不进行回调
            channel.basicNack(deliveryTag, false, true);
        }
    }

//    @RabbitListener(queues = "electronicsQueue")
//    public void receiveElectronicsOrder(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
//        try {
//            // 消费消息的业务逻辑
//            System.out.println("Received electronics order: " + message);
//
//            // 手动确认消息
//            channel.basicAck(deliveryTag, false);
//        } catch (Exception e) {
//            // 消费消息失败,不进行确认,消息重新回到队列中进行重试
//            System.out.println("Failed to process electronics order: " + message);
//            channel.basicNack(deliveryTag, false, true);
//        }
//    }
}
相关推荐
千里码aicood38 分钟前
springboot+vue考研复习交流平台设计(源码+文档+调试+基础修改+答疑)
vue.js·spring boot·后端
王者之座6 小时前
java+maven配置yguard的一次实验
java·spring boot·maven
韩立学长7 小时前
基于Springboot的研学旅游服务系统5u416w14(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·旅游
百***61877 小时前
springboot整合mybatis-plus(保姆教学) 及搭建项目
spring boot·后端·mybatis
武昌库里写JAVA7 小时前
微擎服务器配置要求,微擎云主机多少钱一年?
java·vue.js·spring boot·后端·sql
q***55588 小时前
SpringBoot项目中替换指定版本的tomcat
spring boot·后端·tomcat
汤姆yu8 小时前
基于springboot的电脑商城系统
java·spring boot·后端
麦兜*9 小时前
Redis内存消耗异常飙升?深入排查与Big Key/Hot Key的根治方案
jvm·数据库·spring boot·redis·spring·缓存
q***72569 小时前
Spring Boot + Vue 全栈开发实战指南
vue.js·spring boot·后端
小七mod9 小时前
【Spring】Spring Boot自动配置的案例
java·spring boot·spring·自动配置·源码·ioc·aop