RabbitMQ模块新增消息转换器

文章目录

1.目录结构

2.代码

1.pom.xml 排除logging
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.sunxiansheng</groupId>
        <artifactId>sunrays-common</artifactId>
        <version>1.0.5</version>
    </parent>

    <version>1.0.5</version>

    <artifactId>common-rabbitmq-starter</artifactId>

    <dependencies>
        <!-- 工具包 -->
        <dependency>
            <groupId>com.sunxiansheng</groupId>
            <artifactId>common-tool-starter</artifactId>
            <version>1.0.5</version>
        </dependency>
        <!--AMQP依赖,包含RabbitMQ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-logging</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>
2.RabbitMQConfig.java
java 复制代码
package com.sunxiansheng.rabbitmq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Description: RabbitMQ配置类
 *
 * @Author sun
 * @Create 2025/1/2 14:22
 * @Version 1.0
 */
@Configuration
@AutoConfigureBefore(RabbitAutoConfiguration.class) // 在RabbitAutoConfiguration之前加载,用于覆盖默认的RabbitMQ配置
public class RabbitMQConfig {

    /**
     * 自定义消息转换器,处理JSON和文本消息
     *
     * @return
     */
    @Bean
    public MessageConverter customMessageConverter() {
        return new MessageConverter() {
            private final Jackson2JsonMessageConverter jacksonConverter = new Jackson2JsonMessageConverter();
            private final SimpleMessageConverter simpleMessageConverter = new SimpleMessageConverter();

            /**
             * 发送消息的时候触发
             * @param object
             * @param messageProperties
             * @return
             * @throws RuntimeException
             */
            @Override
            public Message toMessage(Object object, MessageProperties messageProperties) throws RuntimeException {
                if (object instanceof String) {
                    // 如果是字符串,设置为文本类型发送
                    messageProperties.setContentType("text/plain");
                    return simpleMessageConverter.toMessage(object, messageProperties);
                } else {
                    // 默认当作JSON类型处理
                    messageProperties.setContentType("application/json");
                    return jacksonConverter.toMessage(object, messageProperties);
                }
            }

            /**
             * 接收消息的时候触发
             * @param message
             * @return
             * @throws RuntimeException
             */
            @Override
            public Object fromMessage(Message message) throws RuntimeException {
                String contentType = message.getMessageProperties().getContentType();
                // 如果是json类型的数据,就将其自动反序列化为Java对象
                if ("application/json".equals(contentType)) {
                    return jacksonConverter.fromMessage(message);
                    // 如果是文本类型的数据,就将其转换为字符串
                } else if ("text/plain".equals(contentType)) {
                    return simpleMessageConverter.fromMessage(message);
                } else {
                    throw new RuntimeException("自定义的消息转换器不支持该类型: " + contentType);
                }
            }
        };
    }

    /**
     * 设置RabbitTemplate的消息转换器为自定义消息转换器
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 使用自定义消息转换器
        rabbitTemplate.setMessageConverter(customMessageConverter());
        return rabbitTemplate;
    }
}
3.RabbitMQAutoConfiguration.java
java 复制代码
package com.sunxiansheng.rabbitmq.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * Description: RabbitMQ自动配置类
 *
 * @Author sun
 * @Create 2024/12/31 18:44
 * @Version 1.0
 */
@Configuration
@Import(RabbitMQConfig.class)
public class RabbitMQAutoConfiguration {
}
相关推荐
ai_xiaogui1 小时前
【开源前瞻】从“咸鱼”到“超级个体”:谈谈 Panelai 分布式子服务器管理系统的设计架构与 UI 演进
服务器·分布式·架构·分布式架构·panelai·开源面板·ai工具开发
凯子坚持 c2 小时前
如何基于 CANN 原生能力,构建一个支持 QoS 感知的 LLM 推理调度器
分布式
飞升不如收破烂~2 小时前
Redis 分布式锁+接口幂等性使用+当下流行的限流方案「落地实操」+用户连续点击两下按钮的解决方案自用总结
数据库·redis·分布式
无心水2 小时前
分布式定时任务与SELECT FOR UPDATE:从致命陷阱到优雅解决方案(实战案例+架构演进)
服务器·人工智能·分布式·后端·spring·架构·wpf
Lansonli2 小时前
大数据Spark(八十):Action行动算子fold和aggregate使用案例
大数据·分布式·spark
闻哥3 小时前
Kafka高吞吐量核心揭秘:四大技术架构深度解析
java·jvm·面试·kafka·rabbitmq·springboot
invicinble4 小时前
对于分布式的原子能力
分布式
心态还需努力呀13 小时前
CANN仓库通信库:分布式训练的梯度压缩技术
分布式·cann
Coder_Boy_16 小时前
基于SpringAI的在线考试系统-相关技术栈(分布式场景下事件机制)
java·spring boot·分布式·ddd