SpringAMQP入门案例——FanoutExchange交换机

FanoutConfig

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FanoutConfig {

    //声明FanoutExchange交换机
    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange("demo.fanout");
    }

    //声明第一个队列
    @Bean
    public Queue fanoutQueue1() {
        return new Queue("fanout.queue1");
    }

    //绑定队列和交换机
    @Bean
    public Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }

    //声明第二个队列
    @Bean
    public Queue fanoutQueue2() {
        return new Queue("fanout.queue2");
    }

    //绑定队列和交换机
    @Bean
    public Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    }

}

SpringRabbitListener

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "fanout.queue1")
    public void listenQueue1(String message) {
        System.out.println("接收fanout.queue1消息:" + message);
    }

    @RabbitListener(queues = "fanout.queue2")
    public void listenQueue2(String message) {
        System.out.println("接收fanout.queue2消息:" + message);
    }

}

测试

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void test() {
        String exchangeName = "demo.fanout";
        String message = "这是一条消息!";
        rabbitTemplate.convertAndSend(exchangeName, "", message);
    }

查看结果

SpringAMQP入门案例——FanoutExchange交换机_第1张图片

你可能感兴趣的:(其他内容,rabbitmq,spring,boot,java,后端)