Spring Boot整合RabbitMQ

Posted 叶卡捷琳堡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot整合RabbitMQ相关的知识,希望对你有一定的参考价值。

文章目录

一、引入依赖

在Spring Boot项目中引入Spring AMQP依赖

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

二、配置信息

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

三、配置类

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig

    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    public static final String QUEUE_NAME = "boot_queue";

    //交换机配置
    @Bean("bootExchange")
    public Exchange bootExchange()
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    
    //队列配置
    @Bean("bootQueue")
    public Queue bootQueue()
        return QueueBuilder.durable(QUEUE_NAME).build();
    
    //队列和交换机的绑定关系
    @Bean()
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue,@Qualifier("bootExchange") Exchange exchange)
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    


四、生产者编写

使用convertAndSend方法发送消息

@SpringBootTest
class RabbitMqDemo01ApplicationTests 

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void testProducer()
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.Hello","hello");
    

五、消费者编写

编写监听类

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

@Component
public class RabbitMQListener

    @RabbitListener(queues = "boot_queue")
    public void ListenerQueue(Message message)
        System.out.println(new String(message.getBody()));
    

以上是关于Spring Boot整合RabbitMQ的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 整合 RabbitMQ

Spring Boot 整合 RabbitMQ

spring boot 1.5.4 整合rabbitMQ(十七)

Spring Boot 整合 RabbitMQ

Spring Boot整合RabbitMQ

Spring Boot整合RabbitMQ