【訊息佇列】RabbitMq-宣告佇列與交換機

chendsome發表於2024-12-01

透過Spring配置,Bean注入的形式

依賴配置

<!--AMQP依賴,包含RabbitMQ-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

yaml檔案配置

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    virtual-host: /hmall
    username: hmall
    password: 123

fanout交換機

@Configuration
public class FanoutConfiguration {

    @Bean
    public FanoutExchange fanoutExchange(){
        // ExchangeBuilder.fanoutExchange("hmall.fanout2").build();
        return new FanoutExchange("hmall.fanout2");
    }

    @Bean
    public Queue fanoutQueue3(){
        // QueueBuilder.durable("fanout.queue3").build();  // 持久化的佇列,
        return new Queue("fanout.queue3");
    }

    @Bean
    public Binding fanoutBinding3(Queue fanoutQueue3, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue3).to(fanoutExchange);
    }

    @Bean
    public Queue fanoutQueue4(){
        return QueueBuilder.durable("fanout.queue4").build();  // 持久化的佇列,
        // return new Queue("fanout.queue4");
    }

    @Bean
    public Binding fanoutBinding4(){
        return BindingBuilder.bind(fanoutQueue4()).to(fanoutExchange());
    }
}

direct交換機

@Configuration
public class DirectConfiguration {

    @Bean
    public DirectExchange directExchange(){
        // ExchangeBuilder.fanoutExchange("hmall.fanout2").build();
        return new DirectExchange("hmall.direct");
    }

    @Bean
    public Queue directQueue1(){
        // QueueBuilder.durable("fanout.queue3").build();  // 持久化的佇列,
        return new Queue("direct.queue1");
    }

    @Bean
    public Binding directQueue1BindingRed(Queue directQueue1, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue1).to(directExchange).with("red");
    }

    @Bean
    public Binding directQueue1BindingBlue(Queue directQueue1, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue1).to(directExchange).with("blue");
    }

}

註解形式

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1", durable = "true"),
            exchange = @Exchange(name = "hmall.direct", type = ExchangeTypes.DIRECT),
            key = {"blue", "red"}
    ))
    public void listenDirectQueue1(String msg){
        System.err.println("消費者2 收到了direct.queue1的訊息:{" + msg + "}");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2", durable = "true"),
            exchange = @Exchange(name = "hmall.direct", type = ExchangeTypes.DIRECT),
            key = {"yellow", "red"}
    ))
    public void listenDirectQueue2(String msg){
        System.err.println("消費者2 收到了direct.queue2的訊息:{" + msg + "}");
    }

相關文章