服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring Boot RabbitMQ 延迟消息实现完整版示例

Spring Boot RabbitMQ 延迟消息实现完整版示例

2021-04-25 13:20Sam哥哥 Java教程

本篇文章主要介绍了Spring Boot RabbitMQ 延迟消息实现完整版示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

概述

曾经去网易面试的时候,面试官问了我一个问题,说

下完订单后,如果用户未支付,需要取消订单,可以怎么做

我当时的回答是,用定时任务扫描db表即可。面试官不是很满意,提出:

用定时任务无法做到准实时通知,有没有其他办法?

我当时的回答是:

可以用队列,订单下完后,发送一个消息到队列里,并指定过期时间,时间一到,执行回调接口。

面试官听完后,就不再问了。其实我当时的思路是对的,只不过讲的不是很专业而已。专业说法是利用 延迟消息 。

其实用定时任务,确实有点问题,原本业务系统希望10分钟后,如果订单未支付,就马上取消订单,并释放商品库存。但是一旦数据量大的话,就会加长获取未支付订单数据的时间,部分订单就做不到10分钟后取消了,可能是15分钟,20分钟之类的。这样的话,库存就无法及时得到释放,也就会影响成单数。而利用延迟消息,则理论上是可以做到按照设定的时间,进行订单取消操作的。

目前网上关于使用rabbitmq实现延迟消息的文章,大多都是讲如何利用rabbitmq的死信队列来实现,实现方案看起来都很繁琐复杂,并且还是使用原始的rabbitmq client api来实现的,更加显得啰嗦。

spring boot 已经对rabbitmq client api进行了包装,使用起来简洁很多,下面详细介绍一下如何利用 rabbitmq_delayed_message_exchange 插件和spring boot来实现延迟消息。

软件准备

erlang

本文使用的版本是:erlang 20.3

rabbitmq

本文使用的是 window 版本的rabbitmq,版本号是:3.7.4

rabbitmq_delayed_message_exchange插件

插件下载地址:http://www.rabbitmq.com/community-plugins.html

打开网址后,ctrl + f,搜索 rabbitmq_delayed_message_exchange 。

Spring Boot RabbitMQ 延迟消息实现完整版示例

千万记住,一定选好版本号,由于我使用的是rabbitmq 3.7.4,因此对应的 rabbitmq_delayed_message_exchange 插件也必须选择3.7.x的。

如果没有选对版本,在使用延迟消息的时候,会遇到各种各样的奇葩问题,而且网上还找不到解决方案。我因为这个问题,折腾了整整一个晚上。请牢记,要选对插件版本。

下载完插件后,将其放置到rabbitmq安装目录下的 plugins 目录下,并使用如下命令启动这个插件:

rabbitmq-plugins enable rabbitmq_delayed_message_exchange

如果启动成功会出现如下信息:

the following plugins have been enabled:   rabbitmq_delayed_message_exchange

启动插件成功后,记得重启一下rabbitmq,让其生效。

集成rabbitmq

这个就非常简单了,直接在maven工程的pom.xml文件中加入

?
1
2
3
4
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-amqp</artifactid>
</dependency>

spring boot的版本我使用的是 2.0.1.release .

接下来在 application.properties 文件中加入redis配置:

?
1
2
3
4
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

定义connectionfactory和rabbittemplate

也很简单,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.mq.rabbitmq;
 
import org.springframework.amqp.rabbit.connection.cachingconnectionfactory;
import org.springframework.amqp.rabbit.connection.connectionfactory;
import org.springframework.amqp.rabbit.core.rabbittemplate;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
 
@configuration
@configurationproperties(prefix = "spring.rabbitmq")
public class rabbitmqconfig {
  private string host;
  private int port;
  private string username;
  private string password;
 
  @bean
  public connectionfactory connectionfactory() {
    cachingconnectionfactory cachingconnectionfactory = new cachingconnectionfactory(host,port);
    cachingconnectionfactory.setusername(username);
    cachingconnectionfactory.setpassword(password);
    cachingconnectionfactory.setvirtualhost("/");
    cachingconnectionfactory.setpublisherconfirms(true);
    return cachingconnectionfactory;
  }
 
  @bean
  public rabbittemplate rabbittemplate() {
    rabbittemplate rabbittemplate = new rabbittemplate(connectionfactory());
    return rabbittemplate;
  }
 
  public string gethost() {
    return host;
  }
 
  public void sethost(string host) {
    this.host = host;
  }
 
  public int getport() {
    return port;
  }
 
  public void setport(int port) {
    this.port = port;
  }
 
  public string getusername() {
    return username;
  }
 
  public void setusername(string username) {
    this.username = username;
  }
 
  public string getpassword() {
    return password;
  }
 
  public void setpassword(string password) {
    this.password = password;
  }
}

exchange和queue配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.mq.rabbitmq;
 
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
 
import java.util.hashmap;
import java.util.map;
 
@configuration
public class queueconfig {
 
  @bean
  public customexchange delayexchange() {
    map<string, object> args = new hashmap<>();
    args.put("x-delayed-type", "direct");
    return new customexchange("test_exchange", "x-delayed-message",true, false,args);
  }
 
  @bean
  public queue queue() {
    queue queue = new queue("test_queue_1", true);
    return queue;
  }
 
  @bean
  public binding binding() {
    return bindingbuilder.bind(queue()).to(delayexchange()).with("test_queue_1").noargs();
  }
}

这里要特别注意的是,使用的是 customexchange ,不是 directexchange ,另外 customexchange 的类型必须是 x-delayed-message 。

实现消息发送

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.mq.rabbitmq;
 
import org.springframework.amqp.amqpexception;
import org.springframework.amqp.core.message;
import org.springframework.amqp.core.messagepostprocessor;
import org.springframework.amqp.rabbit.core.rabbittemplate;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
 
import java.text.simpledateformat;
import java.util.date;
 
@service
public class messageserviceimpl {
 
  @autowired
  private rabbittemplate rabbittemplate;
 
  public void sendmsg(string queuename,string msg) {
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    system.out.println("消息发送时间:"+sdf.format(new date()));
    rabbittemplate.convertandsend("test_exchange", queuename, msg, new messagepostprocessor() {
      @override
      public message postprocessmessage(message message) throws amqpexception {
        message.getmessageproperties().setheader("x-delay",3000);
        return message;
      }
    });
  }
}

注意在发送的时候,必须加上一个header

x-delay

在这里我设置的延迟时间是3秒。

消息消费者

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.mq.rabbitmq;
import org.springframework.amqp.rabbit.annotation.rabbithandler;
import org.springframework.amqp.rabbit.annotation.rabbitlistener;
import org.springframework.stereotype.component;
 
import java.text.simpledateformat;
import java.util.date;
@component
public class messagereceiver {
 
  @rabbitlistener(queues = "test_queue_1")
  public void receive(string msg) {
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    system.out.println("消息接收时间:"+sdf.format(new date()));
    system.out.println("接收到的消息:"+msg);
  }
}

运行spring boot程序和发送消息

直接在main方法里运行spring boot程序,spring boot会自动解析 messagereceiver 类的。

接下来只需要用junit运行一下发送消息的接口即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.mq.rabbitmq;
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;
@runwith(springrunner.class)
@springboottest
public class rabbitmqapplicationtests {
  @autowired
  private messageserviceimpl messageservice;
  @test
  public void send() {
    messageservice.sendmsg("test_queue_1","hello i am delay msg");
  }
}

运行完后,可以看到如下信息:

消息发送时间:2018-05-03 12:44:53
3秒钟后,spring boot控制台会输出:
消息接收时间:2018-05-03 12:44:56
接收到的消息:hello i am delay msg

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/linsongbin1/article/details/80178122

延伸 · 阅读

精彩推荐