SpringBoot整合RabbitMQ做延时队列

本文介绍了如何使用SpringBoot结合RabbitMQ创建延时队列。RabbitMQ作为消息中间件,主要负责异步处理、解耦以及消息缓冲。文章详细讲解了消息队列的基本概念,交换器的作用,以及在SpringBoot中配置队列、发送和接收消息的步骤。
摘要由CSDN通过智能技术生成

SpringBoot整合RabbitMQ做延时队列

实战前言

RabbitMQ 作为目前应用相当广泛的消息中间件,在企业级应用、微服务应用中充当着重要的角色。特别是在一些典型的应用场景以及业务模块中具有重要的作用,比如业务服务模块解耦、异步通信、高并发限流、超时业务、数据延迟处理等。

RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用。

消息中间件最主要的作用是解耦,中间件最标准的用法是生产者生产消息传送到队列,消费者从队列中拿取消息并处理,生产者不用关心是谁来消费,消费者不用关心谁在生产消息,从而达到解耦的目的。在分布式的系统中,消息队列也会被用在很多其它的方面,比如:分布式事务的支持,RPC的调用等等。

1 消息队列

对于消息队列,我们一般知道有三个概念:发消息者、队列、收消息者,RabbitMQ 在这个基本概念之上,多做了一层抽象,在发消息者和队列之间,加入了交换器(Exchange)这样发消息者和队列就没有直接联系,转而变成发消息者把消息给交换器,交换器根据调度策略再把消息再给队列.

2 交换机

交换机的功能主要是接收消息并且转发到绑定的队列。

交换机类型: Direct类型、Topic类型、Headers类型和Fanout类型。

3 RabbitMQ

RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用。

application.properties
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.listener.concurrency=10
spring.rabbitmq.listener.max-concurrency=20
spring.rabbitmq.listener.prefetch=5
pom文件
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-amqp</artifactId>
  </dependency>
队列配置
 @Configuration
 public class RabbitConfig {

      @Bean
      public Queue helloQueue() {
             return new Queue("hello");
      }

 }
发送者
@Component
public class HelloSender {

     @Autowired
     private AmqpTemplate rabbitTemplate;

     public void send() {
             String context = "hello " + new Date();
             System.out.println("Sender : " + context);
             this.rabbitTemplate.convertAndSend("hello", context);
     }
}
接收者
@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {

     @RabbitHandler
     public void process(String hello) {
            System.out.println("Receiver  : " + hello);
     }

}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {

     @Autowired
     private HelloSender helloSender;


   // 发送单条消息
    @org.junit.Test
    public void contextLoads() {
           helloSender.send();
    }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值