package com.backendsys.modules.common.config.rabbitmq.queue;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * 非懒加载，在项目启动时创建 RabbitMQ 队列、交换机、绑定关系
 */
@Configuration
@Lazy(false)
public class DemoQueueConfig {

    @Autowired
    private DemoDlxQueueConfig config;

    public static final String EXCHANGE = "demo.exchange";
    public static final String QUEUE = "demo.queue";
    public static final String ROUTING_KEY = "demo.create";

    // 交换机
    @Bean
    public DirectExchange demoExchange() {
        return ExchangeBuilder.directExchange(EXCHANGE).durable(true).build();
    }

    // 队列 (5s后过期，1000条后过期)
    @Bean
    public Queue demoQueue() {
        return QueueBuilder.durable(QUEUE)
                .ttl(5000)                    // 5s`
                .maxLength(1000)        // 1000条
                .deadLetterExchange(config.EXCHANGE)
                .deadLetterRoutingKey(config.ROUTING_KEY)
                .build();
    }

    // 队列绑定交换机
    @Bean
    public Binding demoBinding() {
        return BindingBuilder.bind(demoQueue()).to(demoExchange()).with(ROUTING_KEY);
    }


}
