Rabbitmq整合Springboot

一、添加Maven依赖项

    <!-- 1. 父工程依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
        <!--2. rabbitmq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

二、编写yml配置文件,包含rabbitmq的ip、端口、账号、密码和虚拟机等

# 配置RabbitMQ的基本信息  ip 端口 username  password..
spring:
  rabbitmq:
    host: 192.168.100.129 # ip
    port: 5672
    username: guest
    password: guest
    virtual-host: itcast

三、生产者代码

在这里插入图片描述

编写配置文件,配置交换机和队列,代码如下:

@Configuration
public class RabbitMQConfig {
	//定义交换机名
    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    //定义队列名
    public static final String QUEUE_NAME = "boot_queue";
    //1.交换机相关配置
    @Bean("bootExchange")
    public Exchange bootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }
    //2.Queue 队列相关配置
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }
    /*
        1. 知道哪个队列
        2. 知道哪个交换机
        3. routing key
     */
    //3. 队列和交互机绑定 Binding
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }
}

四、消费者代码

在这里插入图片描述

编写一个监听器类即可,监听某个队列的消息,代码如下:

@Component
public class RabbimtMQListener {
	//监听队列名为boot_queue的消息
    @RabbitListener(queues = "boot_queue")
    public void ListenerQueue(Message message){
        //System.out.println(message);
        System.out.println(new String(message.getBody()));
    }
}

五、测试

在生产者工程中编写测试类,代码如下:

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

    //1.注入RabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;

	//发送routingKey为boot.haha,消息内容为boot mq hello~~~的消息
	//EXCHANGE_NAME = "boot_topic_exchange"
    @Test
    public void testSend(){
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
    }
}

1、消息发送之前可以看到消息为0
在这里插入图片描述2、测试类运行后发送消息后,消息队列boot_queue中存储着一条消息
在这里插入图片描述
3、启动消费者的启动类,可以看到控制台打印接收的消息:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值