package com.kym.service.mq.config;

import com.kym.entity.common.Exchanges;
import com.kym.entity.common.Queues;
import com.kym.entity.common.RoutingKeys;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class RabbitConfig {

    /**
     * 延迟交换机的类型
     */
    public static final String DELAY_EXCHANGE_TYPE = "x-delayed-message";

    /**
     * 指定批处理MessageListenerConverter(这里必须设置)
     *
     * @param containerFactory
     * @return
     */
    @Bean
    public String cusSimpleRabbitListenerContainerFactory(SimpleRabbitListenerContainerFactory containerFactory) {
        containerFactory.setBatchListener(true);
        return "cusSimpleRabbitListenerContainerFactory";
    }

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 延迟队列
     *
     * @return
     */
    @Bean(name = "delayQueue")
    public Queue delayQueue() {
        return new Queue(Queues.DELAY_USER_COUPON_QUEUE, true, false, false);
    }


    /**
     * 创建延迟交换机，必须先创建才能监听
     *
     * @return
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        //属性参数 交换机名称 交换机类型 是否持久化 是否自动删除 配置参数
        return new CustomExchange(Exchanges.DELAY_EXCHANGE_NAME, DELAY_EXCHANGE_TYPE, true, false, args);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(RoutingKeys.DELAY_ROUTING_KEY).noargs();
    }


}


