0


SpringBoot集成RabbitMQ(生产者)

默认读者已经对SpringBoot和RabbitMQ比较熟悉

SpringBoot集成RabbitMQ(生产者)的步骤如下:

  1. 创建SpringBoot工程
  2. Maven添加 spring-boot-starter-amqp
  3. 编写application.properties配置RabbitMQ的信息
  4. 编写交换机、队列、绑定配置类
  5. 在业务逻辑代码中注入RabbitTemplate
  6. 调用RabbitTemplate的方法,完成消息推送

1. 添加依赖

在pom.xml添加依赖:

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

2. 编写application.properties

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5276
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/

3. 编写交换机、队列、绑定配置类

2.1 方法一:直接new

Bean配置:

packagecom.lqk.producer;importorg.springframework.amqp.core.*;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;/**
 * @author lqk
 * @Date 2021/6/14
 * @Description
 */@ConfigurationpublicclassProducerConfig{publicstaticfinalString EXCHANGE_NAME ="exchange_name";publicstaticfinalString QUEUE_NAME ="topic_queue_name";@BeanpublicQueuemyQueue(){Queue queue =newQueue(QUEUE_NAME,true,false,false);return queue;}@BeanpublicExchangemyExchange(){FanoutExchange fanoutExchange =newFanoutExchange(EXCHANGE_NAME,true,false);return fanoutExchange;}@BeanpublicBindingmyBinding(@Qualifier("myQueue")Queue queue,@Qualifier("myExchange")Exchange exchange){Binding binding =BindingBuilder.bind(queue).to(exchange).with("test.*").noargs();return binding;}}

2.2 方法二:建造者模式

packagecom.lqk.producer;importorg.springframework.amqp.core.*;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;/**
 * @author 刘乾坤
 * @Date 2021/6/14
 * @Description
 */@ConfigurationpublicclassProducerConfig{publicstaticfinalString EXCHANGE_NAME ="exchange_name";publicstaticfinalString QUEUE_NAME ="topic_queue_name";@BeanpublicQueuemyQueue(){// 持久化构造。  非持久化的构造使用nonDurable,想要定义其它的属性,在build之前继续调用对应的方法设置Queue queue =QueueBuilder.durable(QUEUE_NAME).build();return queue;}@BeanpublicExchangemyExchange(){// 想要定义其它的属性,在build之前继续调用对应的方法设置Exchange build =ExchangeBuilder.fanoutExchange(EXCHANGE_NAME).build();return build;}@BeanpublicBindingmyBinding(@Qualifier("myQueue")Queue queue,@Qualifier("myExchange")Exchange exchange){Binding binding =BindingBuilder.bind(queue).to(exchange).with("test.*").noargs();return binding;}}

4. 注入RabbitTemplate,发送消息

@SpringBootTest@RunWith(SpringRunner.class)classSpringBootRabbitMqProducerApplicationTests{@AutowiredprivateRabbitTemplate rabbitTemplate;@TestvoidcontextLoads(){
        rabbitTemplate.convertAndSend(ProducerConfig.EXCHANGE_NAME,"test.hello","hi~ha");}}

5. 结果

成功创建交换机
image.png

成功创建队列
image.png

成功发送消息

image.png


本文转载自: https://blog.csdn.net/weixin_42606421/article/details/131143359
版权归原作者 仅此而已_ 所有, 如有侵权,请联系我们删除。

“SpringBoot集成RabbitMQ(生产者)”的评论:

还没有评论