SpringBoot整合RabbitMQ(Java注解方式配置)

1.生产端

1. 创建生产者SpringBoot工程

  2. 引入start,依赖坐标

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

  3. 编写yml配置,基本信息配置

spring:
  rabbitmq:
    host:公网ip
    port:5671
    username: 
    password:
    virtual-host:

  4. 定义交换机,队列以及绑定关系的Config配置类

@Configuration
public class RabbitMqConfig {

    //定义交换机的名字
    public static final String  EXCHANGE_NAME = "boot_topic_exchange";
    //定义队列的名字
    public static final String QUEUE_NAME = "boot_queue";

    //1、声明交换机
    @Bean("bootExchange") //bean声明,加入到容器中
    public Exchange bootExchange(){
        //topicExchange: 主题交换机 durable:是否持久化
        //ExchangeBuilder工具类调用topicExchange的API方法创建主题交换机
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    //2、声明队列
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    //3、队列与交换机进行绑定
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }

}

  5. 注入RabbitTemplate,调用方法,完成消息发送

@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {

     //注入 RabbitTemplate
    @Autowired
     private RabbitTemplate  rabbitTemplate;

     @Test
     public void send(){
         rabbitTemplate.convertAndSend("boot_topic_exchange","boot.haha","boot mq...");
     }
}

2.消费端 

1. 创建消费者SpringBoot工程

  2. 引入start,依赖坐标

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

  3. 编写yml配置,基本信息配置

spring:
  rabbitmq:
    host:公网ip
    port:5671
    username: 
    password:
    virtual-host:

  4. 定义监听类,使用@RabbitListener注解完成队列监听。

@Component //声明这是一个组件
public class RabbitMQListener {
      //定义方法进行信息的监听   RabbitListener中的参数用于表示监听的是哪一个队列
    //如果有消息过来,就会执行这个方法,自动会把消息封装到Message对象中,取走消息之后会在队列里删除掉消息
      @RabbitListener(queues = "boot_queue")
      public void ListenerQueue(Message message){
          System.out.println("message:"+message.getBody());
      }
}

3.启动流程

先点击生产端的@test方法发送信息到队列中去,然后直接运行消费端的

@SpringBootApplication启动方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Absinthe_苦艾酒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值