應用場景
我們在使用一些開源排程系統(比如:elastic-job等)的時候,對于任務的執行時間通常都是有規律性的,可能是每隔半小時執行一次,或者每天淩晨一點執行一次。然而實際業務中還存在另外一種定時任務,它可能需要一些觸發條件才開始定時,比如:編寫博文時候,設定2小時之後發送。對于這些開始時間不确定的定時任務,我們也可以通過Spring Cloud Stream來很好的處理。
為了實作開始時間不确定的定時任務觸發,我們将引入延遲消息的使用。RabbitMQ中提供了關于延遲消息的插件,是以本文就來具體介紹以下如何利用Spring Cloud Stream以及RabbitMQ輕松的處理上述問題。
https://blog.didispace.com/spring-cloud-starter-finchley-7-7/#%E5%8A%A8%E6%89%8B%E8%AF%95%E8%AF%95 動手試試
https://blog.didispace.com/spring-cloud-starter-finchley-7-7/#%E6%8F%92%E4%BB%B6%E5%AE%89%E8%A3%85 插件安裝
關于RabbitMQ延遲消息的插件介紹可以檢視官方網站:
https://www.rabbitmq.com/blog/2015/04/16/scheduling-messages-with-rabbitmq/安裝方式很簡單,隻需要在這個頁面:
http://www.rabbitmq.com/community-plugins.html中找到
rabbitmq_delayed_message_exch
ange
插件,根據您使用的RabbitMQ版本選擇對應的插件版本下載下傳即可。
注意:隻有RabbitMQ 3.6.x以上才支援
在下載下傳好之後,解壓得到
.ez
結尾的插件包,将其複制到RabbitMQ安裝目錄下的
plugins
檔案夾。
然後通過指令行啟用該插件:
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
該插件在通過上述指令啟用後就可以直接使用,不需要重新開機。
另外,如果您沒有啟用該插件,您可能為遇到類似這樣的錯誤:
ERROR 156 --- [ 127.0.0.1:5672] o.s.a.r.c.CachingConnectionFactory : Channel shutdown: connection error; protocol method: #method(reply-code=503, reply-text=COMMAND_INVALID - unknown exchange type 'x-delayed-message', class-id=40, method-id=10)
應用編碼
下面通過編寫一個簡單的例子來具體體會一下這個屬性的用法:
@EnableBinding(TestApplication.TestTopic.class)
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Slf4j
@RestController
static class TestController {
@Autowired
private TestTopic testTopic;
/**
* 消息生産接口
*
* @param message
* @return
*/
@GetMapping("/sendMessage")
public String messageWithMQ(@RequestParam String message) {
log.info("Send: " + message);
testTopic.output().send(MessageBuilder.withPayload(message).setHeader("x-delay", 5000).build());
return "ok";
}
}
/**
* 消息消費邏輯
*/
@Slf4j
@Component
static class TestListener {
@StreamListener(TestTopic.INPUT)
public void receive(String payload) {
log.info("Received: " + payload);
}
}
interface TestTopic {
String OUTPUT = "example-topic-output";
String INPUT = "example-topic-input";
@Output(OUTPUT)
MessageChannel output();
@Input(INPUT)
SubscribableChannel input();
}
}
内容很簡單,既包含了消息的生産,也包含了消息消費。在
/sendMessage
接口的定義中,發送了一條消息,一條消息的頭資訊中包含了
x-delay
字段,該字段用來指定消息延遲的時間,機關為毫秒。是以上述代碼發送的消息會在5秒之後被消費。在消息監聽類
TestListener
中,對
TestTopic.INPUT
通道定義了
@StreamListener
,這裡會對延遲消息做具體的邏輯。由于消息的消費是延遲的,進而變相實作了從消息發送那一刻起開始的定時任務。
在啟動應用之前,還要需要做一些必要的配置,下面分消息生産端和消費端做說明:
消息生産端
spring.cloud.stream.bindings.example-topic-output.destination=delay-topic
spring.cloud.stream.rabbit.bindings.example-topic-output.producer.delayed-exchange=true
注意這裡的一個新參數
spring.cloud.stream.rabbit.bindings.example-topic-output.producer.delayed-exchange
,用來開啟延遲消息的功能,這樣在建立exchange的時候,會将其設定為具有延遲特性的exchange,也就是用到上面我們安裝的延遲消息插件的功能。
消息消費端
spring.cloud.stream.bindings.example-topic-input.destination=delay-topic
spring.cloud.stream.bindings.example-topic-input.group=test
spring.cloud.stream.rabbit.bindings.example-topic-input.consumer.delayed-exchange=true
在消費端也一樣,需要設定
spring.cloud.stream.rabbit.bindings.example-topic-output.producer.delayed-exchange=true
。如果該參數不設定,将會出現類似下面的錯誤:
RROR 9340 --- [ 127.0.0.1:5672] o.s.a.r.c.CachingConnectionFactory : Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'type' for exchange 'delay-topic' in vhost '/': received 'topic' but current is ''x-delayed-message'', class-id=40, method-id=10)
完成了上面配置之後,就可以啟動應用,并嘗試通路
localhost:8080/sendMessage?message=hello
接口來發送一個消息到MQ中了。此時可以看到類似下面的日志:
2019-01-02 23:28:45.318 INFO 96164 --- [ctor-http-nio-3] c.d.s.TestApplication$TestController : Send: hello
2019-01-02 23:28:45.328 INFO 96164 --- [ctor-http-nio-3] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [localhost:5672]
2019-01-02 23:28:45.333 INFO 96164 --- [ctor-http-nio-3] o.s.a.r.c.CachingConnectionFactory : Created new connection: rabbitConnectionFactory.publisher#5c5f9a03:0/SimpleConnection@3278a728 [delegate=amqp://[email protected]:5672/, localPort= 53536]
2019-01-02 23:28:50.349 INFO 96164 --- [ay-topic.test-1] c.d.stream.TestApplication$TestListener : Received: hello
從日志中可以看到,
Send: hello
和
Received: hello
兩條輸出之間間隔了5秒,符合我們上面編碼設定的延遲時間。
https://blog.didispace.com/spring-cloud-starter-finchley-7-7/#%E6%B7%B1%E5%85%A5%E6%80%9D%E8%80%83 深入思考
在代碼層面已經完成了定時任務,那麼我們如何檢視延遲的消息數等資訊呢?
此時,我們可以打開RabbitMQ的Web控制台,首先可以進入Exchanges頁面,看看這個特殊exchange,具體如下:
可以看到,這個exchange的Type類型是
x-delayed-message
。點選該exchange的名稱,進入詳細頁面,就可以看到更多具體資訊了:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yYmBjMlFWOjljMxMWZkJmYmZGZ0MmNjZ2MhNGNzQWZ28CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
代碼示例
本文示例讀者可以通過檢視下面倉庫的中的
stream-delayed-message
項目:
如果您對這些感興趣,歡迎star、follow、收藏、轉發給予支援!