package com.muyu.common.rabbit.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Lenovo
 * @Description RabbitMQ连接和管理功能配置
 */

@Configuration
public class RabbitAdminConfig {

    /**
     * RabbitMQ服务器的主机地址
     */
    @Value("${spring.rabbitmq.host}")
    private String host;

    /**
     * RabbitMQ的用户名
     */
    @Value("${spring.rabbitmq.username}")
    private String username;

    /**
     * RabbitMQ的密码
     */
    @Value("${spring.rabbitmq.password}")
    private String password;

    /**
     * RabbitMQ的虚拟主机
     */
    @Value("${spring.rabbitmq.virtualhost}")
    private String virtualhost;

    /**
     * 创建并初始化RabbitAdmin实例
     *
     * @return RabbitAdmin 实例
     */
    @Bean
    public RabbitAdmin rabbitAdmin() {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory());
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    /**
     * 创建RabbitMQ连接工厂
     *
     * @return ConnectionFactory 实例
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(host);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualhost);

        // 配置发送确认回调时，次配置必须配置，否则即使在RabbitTemplate配置了ConfirmCallback也不会生效
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        connectionFactory.setPublisherReturns(true);
        return connectionFactory;
    }
}
