面試官:生成訂單 30 分鐘未支付,則自動取消,該怎麼實現?
在開發中,往往會遇到一些關於延時任務的需求。例如
對上述的任務,我們給一個專業的名字來形容,那就是延時任務。那麼這裏就會產生一個問題,這個延時任務和定時任務的區別究竟在哪裏呢?一共有如下幾點區別
定時任務有執行週期,而延時任務在某事件觸發後一段時間內執行,沒有執行週期
定時任務一般執行的是批處理操作是多個任務,而延時任務一般是單個任務
下面,我們以判斷訂單是否超時爲例,進行方案分析
方案分析
(1) 數據庫輪詢
思路
該方案通常是在小型項目中使用,即通過一個線程定時的去掃描數據庫,通過訂單時間來判斷是否有超時的訂單,然後進行 update 或 delete 等操作
實現
博主當年早期是用 quartz 來實現的 (實習那會的事),簡單介紹一下
maven 項目引入一個依賴如下所示
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.2</version>
</dependency>
調用 Demo 類 MyJob 如下所示
package com.rjzheng.delay1;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJob implements Job {
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("要去數據庫掃描啦。。。");
}
public static void main(String[] args) throws Exception {
// 創建任務
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity("job1", "group1").build();
// 創建觸發器 每3秒鐘執行一次
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("trigger1", "group3")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(3).repeatForever())
.build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// 將任務及其觸發器放入調度器
scheduler.scheduleJob(jobDetail, trigger);
// 調度器開始調度任務
scheduler.start();
}
}
運行代碼,可發現每隔 3 秒,輸出如下
要去數據庫掃描啦。。。
優缺點
優點: 簡單易行,支持集羣操作
缺點:(1) 對服務器內存消耗大
(2) 存在延遲,比如你每隔 3 分鐘掃描一次,那最壞的延遲時間就是 3 分鐘
(3) 假設你的訂單有幾千萬條,每隔幾分鐘這樣掃描一次,數據庫損耗極大
(2)JDK 的延遲隊列
思路
該方案是利用 JDK 自帶的 DelayQueue 來實現,這是一個無界阻塞隊列,該隊列只有在延遲期滿的時候才能從中獲取元素,放入 DelayQueue 中的對象,是必須實現 Delayed 接口的。
DelayedQueue 實現工作流程如下圖所示
其中 Poll(): 獲取並移除隊列的超時元素,沒有則返回空
take(): 獲取並移除隊列的超時元素,如果沒有則 wait 當前線程,直到有元素滿足超時條件,返回結果。
實現
定義一個類 OrderDelay 實現 Delayed,代碼如下
package com.rjzheng.delay2;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class OrderDelay implements Delayed {
private String orderId;
private long timeout;
OrderDelay(String orderId, long timeout) {
this.orderId = orderId;
this.timeout = timeout + System.nanoTime();
}
public int compareTo(Delayed other) {
if (other == this)
return 0;
OrderDelay t = (OrderDelay) other;
long d = (getDelay(TimeUnit.NANOSECONDS) - t
.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
}
// 返回距離你自定義的超時時間還有多少
public long getDelay(TimeUnit unit) {
return unit.convert(timeout - System.nanoTime(),TimeUnit.NANOSECONDS);
}
void print() {
System.out.println(orderId+"編號的訂單要刪除啦。。。。");
}
}
運行的測試 Demo 爲,我們設定延遲時間爲 3 秒
package com.rjzheng.delay2;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
public class DelayQueueDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = new ArrayList<String>();
list.add("00000001");
list.add("00000002");
list.add("00000003");
list.add("00000004");
list.add("00000005");
DelayQueue<OrderDelay> queue = newDelayQueue<OrderDelay>();
long start = System.currentTimeMillis();
for(int i = 0;i<5;i++){
//延遲三秒取出
queue.put(new OrderDelay(list.get(i),
TimeUnit.NANOSECONDS.convert(3,TimeUnit.SECONDS)));
try {
queue.take().print();
System.out.println("After " +
(System.currentTimeMillis()-start) + " MilliSeconds");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
輸出如下
00000001編號的訂單要刪除啦。。。。
After 3003 MilliSeconds
00000002編號的訂單要刪除啦。。。。
After 6006 MilliSeconds
00000003編號的訂單要刪除啦。。。。
After 9006 MilliSeconds
00000004編號的訂單要刪除啦。。。。
After 12008 MilliSeconds
00000005編號的訂單要刪除啦。。。。
After 15009 MilliSeconds
可以看到都是延遲 3 秒,訂單被刪除
優缺點
優點: 效率高, 任務觸發時間延遲低。
缺點:
(1) 服務器重啓後,數據全部消失,怕宕機 (2) 集羣擴展相當麻煩 (3) 因爲內存條件限制的原因,比如下單未付款的訂單數太多,那麼很容易就出現 OOM 異常 (4) 代碼複雜度較高
(3) 時間輪算法
思路
先上一張時間輪的圖 (這圖到處都是啦)
時間輪算法可以類比於時鍾,如上圖箭頭(指針)按某一個方向按固定頻率輪動,每一次跳動稱爲一個 tick。這樣可以看出定時輪由個 3 個重要的屬性參數,ticksPerWheel(一輪的 tick 數),tickDuration(一個 tick 的持續時間)以及 timeUnit(時間單位),例如當 ticksPerWheel=60,tickDuration=1,timeUnit = 秒,這就和現實中的始終的秒針走動完全類似了。
如果當前指針指在 1 上面,我有一個任務需要 4 秒以後執行,那麼這個執行的線程回調或者消息將會被放在 5 上。那如果需要在 20 秒之後執行怎麼辦,由於這個環形結構槽數只到 8,如果要 20 秒,指針需要多轉 2 圈。位置是在 2 圈之後的 5 上面(20 % 8 + 1)
實現
我們用 Netty 的 HashedWheelTimer 來實現
給 Pom 加上下面的依賴
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.24.Final</version>
</dependency>
測試代碼 HashedWheelTimerTest 如下所示
package com.rjzheng.delay3;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class HashedWheelTimerTest {
static class MyTimerTask implements TimerTask{
boolean flag;
public MyTimerTask(boolean flag){
this.flag = flag;
}
public void run(Timeout timeout) throws Exception {
// TODO Auto-generated method stub
System.out.println("要去數據庫刪除訂單了。。。。");
this.flag =false;
}
}
public static void main(String[] argv) {
MyTimerTask timerTask = new MyTimerTask(true);
Timer timer = new HashedWheelTimer();
timer.newTimeout(timerTask, 5, TimeUnit.SECONDS);
int i = 1;
while(timerTask.flag){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i+"秒過去了");
i++;
}
}
}
輸出如下
1秒過去了
2秒過去了
3秒過去了
4秒過去了
5秒過去了
要去數據庫刪除訂單了。。。。
6秒過去了
優缺點
優點: 效率高, 任務觸發時間延遲時間比 delayQueue 低,代碼複雜度比 delayQueue 低。
缺點:
(1) 服務器重啓後,數據全部消失,怕宕機
(2) 集羣擴展相當麻煩
(3) 因爲內存條件限制的原因,比如下單未付款的訂單數太多,那麼很容易就出現 OOM 異常
(4)redis 緩存
思路一
利用 redis 的 zset,zset 是一個有序集合,每一個元素 (member) 都關聯了一個 score, 通過 score 排序來取集合中的值
添加元素: ZADD key score member [[score member] [score member] …]
按順序查詢元素: ZRANGE key start stop [WITHSCORES]
查詢元素 score:ZSCORE key member
移除元素: ZREM key member [member …]
測試如下
添加單個元素
redis> ZADD page_rank 10 google.com
(integer) 1
添加多個元素
redis> ZADD page_rank 9 baidu.com 8 bing.com
(integer) 2
redis> ZRANGE page_rank 0 -1 WITHSCORES
1) "bing.com"
2) "8"
3) "baidu.com"
4) "9"
5) "google.com"
6) "10"
查詢元素的score值
redis> ZSCORE page_rank bing.com
"8"
移除單個元素
redis> ZREM page_rank google.com
(integer) 1
redis> ZRANGE page_rank 0 -1 WITHSCORES
1) "bing.com"
2) "8"
3) "baidu.com"
4) "9"
那麼如何實現呢?我們將訂單超時時間戳與訂單號分別設置爲 score 和 member, 系統掃描第一個元素判斷是否超時,具體如下圖所示
實現一
package com.rjzheng.delay4;
import java.util.Calendar;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;
public class AppTest {
private static final String ADDR = "127.0.0.1";
private static final int PORT = 6379;
private static JedisPool jedisPool = new JedisPool(ADDR, PORT);
public static Jedis getJedis() {
return jedisPool.getResource();
}
//生產者,生成5個訂單放進去
public void productionDelayMessage(){
for(int i=0;i<5;i++){
//延遲3秒
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.SECOND, 3);
int second3later = (int) (cal1.getTimeInMillis() / 1000);
AppTest.getJedis().zadd("OrderId",second3later,"OID0000001"+i);
System.out.println(System.currentTimeMillis()+"ms:redis生成了一個訂單任務:訂單ID爲"+"OID0000001"+i);
}
}
//消費者,取訂單
public void consumerDelayMessage(){
Jedis jedis = AppTest.getJedis();
while(true){
Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1);
if(items == null || items.isEmpty()){
System.out.println("當前沒有等待的任務");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
}
int score = (int) ((Tuple)items.toArray()[0]).getScore();
Calendar cal = Calendar.getInstance();
int nowSecond = (int) (cal.getTimeInMillis() / 1000);
if(nowSecond >= score){
String orderId = ((Tuple)items.toArray()[0]).getElement();
jedis.zrem("OrderId", orderId);
System.out.println(System.currentTimeMillis() +"ms:redis消費了一個任務:消費的訂單OrderId爲"+orderId);
}
}
}
public static void main(String[] args) {
AppTest appTest =new AppTest();
appTest.productionDelayMessage();
appTest.consumerDelayMessage();
}
}
此時對應輸出如下
可以看到,幾乎都是 3 秒之後,消費訂單。
然而,這一版存在一個致命的硬傷,在高併發條件下,多消費者會取到同一個訂單號,我們上測試代碼 ThreadTest
package com.rjzheng.delay4;
import java.util.concurrent.CountDownLatch;
public class ThreadTest {
private static final int threadNum = 10;
private static CountDownLatch cdl = newCountDownLatch(threadNum);
static class DelayMessage implements Runnable{
public void run() {
try {
cdl.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AppTest appTest =new AppTest();
appTest.consumerDelayMessage();
}
}
public static void main(String[] args) {
AppTest appTest =new AppTest();
appTest.productionDelayMessage();
for(int i=0;i<threadNum;i++){
new Thread(new DelayMessage()).start();
cdl.countDown();
}
}
}
輸出如下所示
顯然,出現了多個線程消費同一個資源的情況。
解決方案
(1) 用分佈式鎖,但是用分佈式鎖,性能下降了,該方案不細說。
(2) 對 ZREM 的返回值進行判斷,只有大於 0 的時候,才消費數據,於是將 consumerDelayMessage() 方法裏的
if(nowSecond >= score){
String orderId = ((Tuple)items.toArray()[0]).getElement();
jedis.zrem("OrderId", orderId);
System.out.println(System.currentTimeMillis()+"ms:redis消費了一個任務:消費的訂單OrderId爲"+orderId);
}
修改爲
if(nowSecond >= score){
String orderId = ((Tuple)items.toArray()[0]).getElement();
Long num = jedis.zrem("OrderId", orderId);
if( num != null && num>0){
System.out.println(System.currentTimeMillis()+"ms:redis消費了一個任務:消費的訂單OrderId爲"+orderId);
}
}
在這種修改後,重新運行 ThreadTest 類,發現輸出正常了
思路二
該方案使用 redis 的 Keyspace Notifications,中文翻譯就是鍵空間機制,就是利用該機制可以在 key 失效之後,提供一個回調,實際上是 redis 會給客戶端發送一個消息。是需要 redis 版本 2.8 以上。
實現二
在 redis.conf 中,加入一條配置
notify-keyspace-events Ex
運行代碼如下
package com.rjzheng.delay5;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;
public class RedisTest {
private static final String ADDR = "127.0.0.1";
private static final int PORT = 6379;
private static JedisPool jedis = new JedisPool(ADDR, PORT);
private static RedisSub sub = new RedisSub();
public static void init() {
new Thread(new Runnable() {
public void run() {
jedis.getResource().subscribe(sub, "__keyevent@0__:expired");
}
}).start();
}
public static void main(String[] args) throws InterruptedException {
init();
for(int i =0;i<10;i++){
String orderId = "OID000000"+i;
jedis.getResource().setex(orderId, 3, orderId);
System.out.println(System.currentTimeMillis()+"ms:"+orderId+"訂單生成");
}
}
static class RedisSub extends JedisPubSub {
<ahref='http://www.jobbole.com/members/wx610506454'>@Override</a>
public void onMessage(String channel, String message) {
System.out.println(System.currentTimeMillis()+"ms:"+message+"訂單取消");
}
}
}
輸出如下
可以明顯看到 3 秒過後,訂單取消了
ps:redis 的 pub/sub 機制存在一個硬傷,官網內容如下
原: Because Redis Pub/Sub is fire and forget currently there is no way to use this feature if your application demands reliable notification of events, that is, if your Pub/Sub client disconnects, and reconnects later, all the events delivered during the time the client was disconnected are lost.
翻: Redis 的發佈 / 訂閱目前是即發即棄 (fire and forget) 模式的,因此無法實現事件的可靠通知。也就是說,如果發佈 / 訂閱的客戶端斷鏈之後又重連,則在客戶端斷鏈期間的所有事件都丟失了。因此,方案二不是太推薦。當然,如果你對可靠性要求不高,可以使用。
優缺點
優點:(1) 由於使用 Redis 作爲消息通道,消息都存儲在 Redis 中。如果發送程序或者任務處理程序掛了,重啓之後,還有重新處理數據的可能性。(2) 做集羣擴展相當方便 (3) 時間準確度高
缺點:(1) 需要額外進行 redis 維護
(5) 使用消息隊列
我們可以採用 rabbitMQ 的延時隊列。RabbitMQ 具有以下兩個特性,可以實現延遲隊列
RabbitMQ 可以針對 Queue 和 Message 設置 x-message-tt,來控制消息的生存時間,如果超時,則消息變爲 dead letter
lRabbitMQ 的 Queue 可以配置 x-dead-letter-exchange 和 x-dead-letter-routing-key(可選)兩個參數,用來控制隊列內出現了 deadletter,則按照這兩個參數重新路由。結合以上兩個特性,就可以模擬出延遲消息的功能, 具體的,我改天再寫一篇文章,這裏再講下去,篇幅太長。
優缺點
優點: 高效, 可以利用 rabbitmq 的分佈式特性輕易的進行橫向擴展, 消息支持持久化增加了可靠性。
缺點:本身的易用度要依賴於 rabbitMq 的運維. 因爲要引用 rabbitMq, 所以複雜度和成本變高
作者:hjm4702192
來源:blog.csdn.net/hjm4702192/article/details/80519010
架構師
我們都是架構師!
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/DfCiGZ7WmaELCBxc-LE6XQ