SpringBootRabbitMQ延遲消息實(shí)現(xiàn)完整版示例

概述

創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),沙市企業(yè)網(wǎng)站建設(shè),沙市品牌網(wǎng)站建設(shè),網(wǎng)站定制,沙市網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,沙市網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。

曾經(jīng)去網(wǎng)易面試的時(shí)候,面試官問了我一個(gè)問題,說

下完訂單后,如果用戶未支付,需要取消訂單,可以怎么做

我當(dāng)時(shí)的回答是,用定時(shí)任務(wù)掃描DB表即可。面試官不是很滿意,提出:

用定時(shí)任務(wù)無法做到準(zhǔn)實(shí)時(shí)通知,有沒有其他辦法?

我當(dāng)時(shí)的回答是:

可以用隊(duì)列,訂單下完后,發(fā)送一個(gè)消息到隊(duì)列里,并指定過期時(shí)間,時(shí)間一到,執(zhí)行回調(diào)接口。

面試官聽完后,就不再問了。其實(shí)我當(dāng)時(shí)的思路是對(duì)的,只不過講的不是很專業(yè)而已。專業(yè)說法是利用 延遲消息 。

其實(shí)用定時(shí)任務(wù),確實(shí)有點(diǎn)問題,原本業(yè)務(wù)系統(tǒng)希望10分鐘后,如果訂單未支付,就馬上取消訂單,并釋放商品庫存。但是一旦數(shù)據(jù)量大的話,就會(huì)加長(zhǎng)獲取未支付訂單數(shù)據(jù)的時(shí)間,部分訂單就做不到10分鐘后取消了,可能是15分鐘,20分鐘之類的。這樣的話,庫存就無法及時(shí)得到釋放,也就會(huì)影響成單數(shù)。而利用延遲消息,則理論上是可以做到按照設(shè)定的時(shí)間,進(jìn)行訂單取消操作的。

目前網(wǎng)上關(guān)于使用RabbitMQ實(shí)現(xiàn)延遲消息的文章,大多都是講如何利用RabbitMQ的死信隊(duì)列來實(shí)現(xiàn),實(shí)現(xiàn)方案看起來都很繁瑣復(fù)雜,并且還是使用原始的RabbitMQ Client API來實(shí)現(xiàn)的,更加顯得啰嗦。

Spring Boot 已經(jīng)對(duì)RabbitMQ Client API進(jìn)行了包裝,使用起來簡(jiǎn)潔很多,下面詳細(xì)介紹一下如何利用 rabbitmq_delayed_message_exchange 插件和Spring Boot來實(shí)現(xiàn)延遲消息。

軟件準(zhǔn)備

erlang

本文使用的版本是:Erlang 20.3

RabbitMQ

本文使用的是 window 版本的RabbitMQ,版本號(hào)是:3.7.4

rabbitmq_delayed_message_exchange插件

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

打開網(wǎng)址后,ctrl + f,搜索 rabbitmq_delayed_message_exchange 。

Spring Boot RabbitMQ 延遲消息實(shí)現(xiàn)完整版示例

千萬記住,一定選好版本號(hào),由于我使用的是RabbitMQ 3.7.4,因此對(duì)應(yīng)的 rabbitmq_delayed_message_exchange 插件也必須選擇3.7.x的。

如果沒有選對(duì)版本,在使用延遲消息的時(shí)候,會(huì)遇到各種各樣的奇葩問題,而且網(wǎng)上還找不到解決方案。我因?yàn)檫@個(gè)問題,折騰了整整一個(gè)晚上。請(qǐng)牢記,要選對(duì)插件版本。

下載完插件后,將其放置到RabbitMQ安裝目錄下的 plugins 目錄下,并使用如下命令啟動(dòng)這個(gè)插件:

rabbitmq-plugins enable rabbitmq_delayed_message_exchange

如果啟動(dòng)成功會(huì)出現(xiàn)如下信息:

The following plugins have been enabled:   rabbitmq_delayed_message_exchange

啟動(dòng)插件成功后,記得重啟一下RabbitMQ,讓其生效。

集成RabbitMQ

這個(gè)就非常簡(jiǎn)單了,直接在maven工程的pom.xml文件中加入

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

Spring Boot的版本我使用的是 2.0.1.RELEASE .

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

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

定義ConnectionFactory和RabbitTemplate

也很簡(jiǎn)單,代碼如下:

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配置

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 。

實(shí)現(xiàn)消息發(fā)送

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("消息發(fā)送時(shí)間:"+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;
      }
    });
  }
}

注意在發(fā)送的時(shí)候,必須加上一個(gè)header

x-delay

在這里我設(shè)置的延遲時(shí)間是3秒。

消息消費(fèi)者

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("消息接收時(shí)間:"+sdf.format(new Date()));
    System.out.println("接收到的消息:"+msg);
  }
}

運(yùn)行Spring Boot程序和發(fā)送消息

直接在main方法里運(yùn)行Spring Boot程序,Spring Boot會(huì)自動(dòng)解析 MessageReceiver 類的。

接下來只需要用Junit運(yùn)行一下發(fā)送消息的接口即可。

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");
  }
}

運(yùn)行完后,可以看到如下信息:

消息發(fā)送時(shí)間:2018-05-03 12:44:53
3秒鐘后,Spring Boot控制臺(tái)會(huì)輸出:
消息接收時(shí)間:2018-05-03 12:44:56
接收到的消息:hello i am delay msg

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

新聞標(biāo)題:SpringBootRabbitMQ延遲消息實(shí)現(xiàn)完整版示例
網(wǎng)址分享:http://muchs.cn/article46/ijcdhg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)外貿(mào)建站、小程序開發(fā)、網(wǎng)站排名網(wǎng)站收錄、全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)