package com.muyu.car.gateway.mq;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;


/**
 * @Author：蓬叁
 * @Package：com.muyu.car.gateway.mq
 * @Project：cloud-server-8
 * @name：CreateExchange
 * @Date：2024/10/7 下午8:53
 */
@Log4j2
@Component
public class CreateExchange implements ApplicationRunner {

    @Autowired
    private ConnectionFactory connectionFactory;

    @Override
    public void run(ApplicationArguments args)  {
        log.info("=====>开始创建交换机");

        try {
            RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);

            // 创建Fanout类型的交换机
            FanoutExchange exchange = new FanoutExchange("ONLINE_EXCHANGE", true, false);

            rabbitAdmin.declareExchange(exchange);

            // 创建队列
            Queue queue = new Queue("GO_ONLINE", true, false, false);

            rabbitAdmin.declareQueue(queue);

            // Fanout交换机绑定
            rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange));

            log.info("=====>交换机创建成功");
            log.info("=====>队列创建成功并绑定到交换机");
        }catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}
