SpringBoot 整合 RabbitMQ 步骤

2020-11-24  本文已影响0人  bin丶

一、安装软件


二、pom.xml 配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency> 

三、yml配置 - 生产者和消费者一致

# 可以指定自己设置的虚拟路径和用户
spring:
  rabbitmq:
    host: localhost
    port: 5672
    virtual-host: /  
    username: guest
    password: guest

四、生产者(producer)配置

@Configuration
public class RabbitMQConfig {

    // 交换机名称
    public static final String EXCHANGE_NAME = "spingboot_topic_exchange";
    // 队列名称
    public static final String QUEUE_NAME = "topic_queue";

    // 声明交换机
    @Bean("topicExchange")
    public Exchange topicExchange(){

        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    // 声明队列
    @Bean("topicQueue")
    public Queue topicQueue(){

        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    // 绑定
    @Bean
    public Binding topicBinding(@Qualifier("topicQueue") Queue queue, @Qualifier("topicExchange") Exchange exchange){
        // 绑定队列与交换机,并设置路由key = topic.#
        return BindingBuilder.bind(queue).to(exchange).with("topic.#").noargs();
    }
}

五、消费者(consumer)代码

@Component
public class Mylistener {
    // 队列名称与生产者定义的要一致
    @RabbitListener(queues = "topic_queue")
    public void myListener1(String message) {
        System.out.println("消费者接收到消息: " + message);
    }
}

六、测试(producer)代码

@SpringBootTest
class ProducerApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void contextLoads() {
        //  将消息按指定路由key发送到交换机
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                "topic.insert", "test msg1");
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                "topic.update", "test msg2");
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                "topic.delete", "test msg3");
    }

}
上一篇下一篇

猜你喜欢

热点阅读