package com.muyu.common.rabbit.config;

import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;

/**
 * @author Lenovo
 * @Description rabbitMQ的监听器配置
 */

@Configuration
public class RabbitListenerConfig implements RabbitListenerConfigurer {

    static {
        // 设置为信任所有类型的反序列化，确保消息能够正确反序列化
        System.setProperty("spring.amqp.deserialization.trust.all", "true");
    }

    /**
     * RabbitMQ连接工厂，用于创建连接
     */
    @Autowired
    public ConnectionFactory connectionFactory;


    /**
     * 创建处理器方法工厂的bean
     *
     * @return DefaultMessageHandlerMethodFactory 实例，用于处理消息的转换和方法调用
     */
    @Bean
    public DefaultMessageHandlerMethodFactory handlerMethodFactory() {
        DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
        // 这里的转换器设置实现了 通过 @Payload 注解 自动反序列化message body
        factory.setMessageConverter(new MappingJackson2MessageConverter());
        return factory;
    }

    /**
     * 配置RabbitMQ监听器的消息处理方法工厂。
     *
     * @param rabbitListenerEndpointRegistrar 实例，用于注册监听器的配置
     */
    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar rabbitListenerEndpointRegistrar) {
        // 注册自定义的消息处理方法工厂
        rabbitListenerEndpointRegistrar.setMessageHandlerMethodFactory(handlerMethodFactory());
    }

}

