交换机(exchange)

在真实的生产环境中,我们并不会直接将消息发送到队列(queue),而是将消息发送到交换机(exchange),再由交换机发送到队列。

交换机的功能:1. 接收来自生产者的消息;2. 将消息推入队列。

交换机的类型有以下三种:

  • Fanout:该类型的交换机不分析Routing Key,将接收到的消息转发给所有和该交换机绑定的队列中。

  • Direct:该类型的交换机需要精准匹配Routing Key,直会将消息转发到指定Routing Key的队列中。

  • Topic:该类交换机按照一定规则匹配Routing Key,将消息转发到匹配的队列中

Fanout 交换机

Drawing
// 交换机名
String exchangeName = "test.exchange";
// 消息内容
String message = "hello world";
// 发送消息, 参数:交换机名,路由键,消息内容
rabbitTemplate.convertAndSend(exchangeName, null, message);

Direct 交换机

Topic 交换机

Java 代码声明交换机

SpringAMQP 提供了几个类,用来声明队列,交换机及其绑定关系:

  • Queue:用于声明队列,可以用工厂类QueueBuilder构建。

  • Exchange:用于声明交换机,可以用工厂类ExchangeBuilder构建。

  • Binding:用于声明队列和交换机的绑定关系,可以用工厂类BindingBuilder构建。

基于Bean声明

@Configuration
public class SpringAmqpConfiguration {
    // 声明队列
    @Bean
    public Queue workQueue() {
        // return QueueBuilder.durable("work.queue").build();
        return new Queue("work.queue");
    }

    // 声明交换机
    @Bean
    public DirectExchange workExchange() {
        // return ExchangeBuilder.directExchange("work.exchange").build();
        return new DirectExchange("work.exchange");
    }

    // 绑定
    @Bean
    public Binding workBinding() {
        return BindingBuilder.bind(workQueue()).to(workExchange()).with("work.routing.key");
    }
}

基于注解来创建

@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "work.queue", durable = "true"),
        exchange = @Exchange(value = "work.fanoutExchange", type = ExchangeTypes.FANOUT),
        key = {"work.routing.key"}
))
public void receive(String message) {
    System.out.println("message = " + message);
}

最后更新于

这有帮助吗?