SpringBoot整合RabbitMQ

本文介绍如何在Spring Boot应用中配置并使用RabbitMQ消息队列,包括依赖配置、消息队列定义、生产者与消费者实现及测试流程。通过具体代码示例,展示了下单减库存和发放权益两种场景下的消息发送与接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置依赖

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

 

配置参数

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

 

消息队列

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName: Queues
 * @Description: Queues
 * @Author: xuezhouyi
 * @Version: V1.0
 **/
@Configuration
public class Queues {

    /**
     * 下单减库存
     */
    public static final String CP_ORDER_OPS = "cp:order:ops";

    /**
     * 发放权益
     */
    public static final String CP_RIGHTS_OPS = "cp:rights:ops";

    @Bean
    public Queue orderOps() {
        return new Queue(CP_ORDER_OPS);
    }

    @Bean
    public Queue rightsOps() {
        return new Queue(CP_RIGHTS_OPS);
    }
}

 

生产者

import com.icitic.mc.seckill.service.config.Queues;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: Producer
 * @Description: Producer
 * @Author: xuezhouyi
 * @Version: V1.0
 **/
@Component
public class Producer {
    @Autowired
    private AmqpTemplate template;

    public void orderMQ() {
        template.convertAndSend(Queues.CP_ORDER_OPS, "下单");
        System.out.println(">>>下单消息发送成功!");
    }

    public void rightsMQ() {
        template.convertAndSend(Queues.CP_RIGHTS_OPS, "权益");
        System.out.println(">>>权益消息发送成功!");
    }
}

 

消费者

import com.icitic.mc.seckill.service.config.Queues;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName: Consumer
 * @Description: Consumer
 * @Author: xuezhouyi
 * @Version: V1.0
 **/
@Component
public class Consumer {
    @RabbitListener(queues = Queues.CP_ORDER_OPS)
    public void consumerOrder(String str) throws InterruptedException {
        Thread.sleep(1000);
        System.out.println(">>>下单收到消息:" + str);
    }

    @RabbitListener(queues = Queues.CP_RIGHTS_OPS)
    public void consumerRights(String str) {
        System.out.println(">>>权益收到消息:" + str);
    }
}

 

测试

import com.icitic.mc.seckill.service.mq.Producer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @ClassName: SecKillServiceApplicationTests
 * @Description: SecKillServiceApplicationTests
 * @Author: xuezhouyi
 * @Version: V1.0
 **/
@SpringBootTest
@RunWith(SpringRunner.class)
public class SecKillServiceApplicationTests {
    @Autowired
    public Producer producer;

    @Test
    public void test() throws InterruptedException {
        producer.orderMQ();
        Thread.sleep(1000);
        producer.rightsMQ();
    }
}

 

结果

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

20:20:16.345   [main] INFO  {org.springframework.boot.StartupInfoLogger: logStarted} com.icitic.mc.seckill.service.service.SecKillServiceApplicationTests : Started SecKillServiceApplicationTests in 19.715 seconds (JVM running for 21.842)
>>>下单消息发送成功!
>>>权益消息发送成功!

20:20:16.903   [Thread-8] INFO  {org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer: doShutdown} org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer : Waiting for workers to finish.
>>>权益收到消息:权益
20:20:16.961   [Thread-8] INFO  {org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer: doShutdown} org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer : Successfully waited for workers to finish.
20:20:17.005   [Thread-8] INFO  {org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer: doShutdown} org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer : Waiting for workers to finish.
>>>下单收到消息:下单
20:20:17.965   [Thread-8] INFO  {org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer: doShutdown} org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer : Successfully waited for workers to finish.

Spring Boot框架可以很容易地与RabbitMQ进行集成。为了实现这个目标,你需要在项目的依赖项中添加两个关键的依赖项。首先,你需要添加spring-boot-starter-amqp依赖项,它提供了与RabbitMQ进行通信的必要类和方法。其次,你还需要添加spring-boot-starter-web依赖项,以便在项目中使用Web功能。 在你的项目中创建两个Spring Boot应用程序,一个是RabbitMQ的生产者,另一个是消费者。通过这两个应用程序,你可以实现消息的发送和接收。生产者应用程序负责将消息发送到RabbitMQ的消息队列,而消费者应用程序则负责从队列中接收并处理消息。这样,你就可以实现基于RabbitMQ的消息传递系统。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合RabbitMQ](https://blog.csdn.net/K_kzj_K/article/details/106642250)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Springboot 整合RabbitMq ,用心看完这一篇就够了](https://blog.csdn.net/qq_35387940/article/details/100514134)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [undefined](undefined)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值