SpringBoot整合Rabbitmq

步骤


创建一个Boot项目 导入rabbitmq依赖

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

编写yml配置文件

spring:
  rabbitmq:
    host: 192.168.198.129
    port: 5672
    username: admin
    password: admin
    virtual-host: /

编写生产者

编写一个配置类 在配置类里面给出队列 交换机 以及绑定关系

package com.jie.config;

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 bingQueueExchange(@Qualifier("bootQueue") Queue queue,@Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }
}

在使用时我们需要用到RabbitTemplate类去进行操作

@SpringBootTest
class RabbitmqDemo01ApplicationTests {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Test
    void contextLoads() {
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","hello boot and mq");
    }
}

编写消费者

消费者会比较简单一点
定义一个监听者类 给出要监听的队列即可

package com.jie;

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(message);
    }
}

在启动boot项目后 后台监听就会自动启动 如下图启动项目自动拿到了前面生产者发出去的消息

posted @ 2021-10-04 15:38  一个经常掉线的人  阅读(158)  评论(0编辑  收藏  举报