Redis 延時(shí)任務(wù)
引言
生成訂單30分鐘未支付,則自動取消 生成訂單60秒后,給用戶發(fā)短信
定時(shí)任務(wù)有明確的觸發(fā)時(shí)間,延時(shí)任務(wù)沒有 定時(shí)任務(wù)有執(zhí)行周期,而延時(shí)任務(wù)在某事件觸發(fā)后一段時(shí)間內(nèi)執(zhí)行,沒有執(zhí)行周期 定時(shí)任務(wù)一般執(zhí)行的是批處理操作是多個(gè)任務(wù),而延時(shí)任務(wù)一般是單個(gè)任務(wù)
方案分析
(1) 數(shù)據(jù)庫輪詢
<dependency>
??<groupId>org.quartz-schedulergroupId>
??<artifactId>quartzartifactId>
??<version>2.2.2version>
dependency>
public?class?MyJob?implements?Job?{
????public?void?execute(JobExecutionContext?context)
????????throws?JobExecutionException?{
????????System.out.println("要去數(shù)據(jù)庫掃描啦。。。");
????}
????public?static?void?main(String[]?args)?throws?Exception?{
????????//?創(chuàng)建任務(wù)
????????JobDetail?jobDetail?=?JobBuilder.newJob(MyJob.class)
????????????????????????????????????????.withIdentity("job1",?"group1").build();
????????//?創(chuàng)建觸發(fā)器?每3秒鐘執(zhí)行一次
????????Trigger?trigger?=?TriggerBuilder.newTrigger()
????????????????????????????????????????.withIdentity("trigger1",?"group3")
????????????????????????????????????????.withSchedule(SimpleScheduleBuilder.simpleSchedule()
???????????????????????????????????????????????????????????????????????????.withIntervalInSeconds(3)
???????????????????????????????????????????????????????????????????????????.repeatForever())
????????????????????????????????????????.build();
????????Scheduler?scheduler?=?new?StdSchedulerFactory().getScheduler();
????????//?將任務(wù)及其觸發(fā)器放入調(diào)度器
????????scheduler.scheduleJob(jobDetail,?trigger);
????????//?調(diào)度器開始調(diào)度任務(wù)
????????scheduler.start();
????}
}
要去數(shù)據(jù)庫掃描啦。。。
優(yōu)缺點(diǎn)
簡單易行,支持集群操作
對服務(wù)器內(nèi)存消耗大 存在延遲,比如你每隔3分鐘掃描一次,那最壞的延遲時(shí)間就是3分鐘 假設(shè)你的訂單有幾千萬條,每隔幾分鐘這樣掃描一次,數(shù)據(jù)庫損耗極大
(2) JDK的延遲隊(duì)列

Poll():獲取并移除隊(duì)列的超時(shí)元素,沒有則返回空take():獲取并移除隊(duì)列的超時(shí)元素,如果沒有則wait當(dāng)前線程,直到有元素滿足超時(shí)條件,返回結(jié)果。
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);
????}
????//?返回距離你自定義的超時(shí)時(shí)間還有多少
????public?long?getDelay(TimeUnit?unit)?{
????????return?unit.convert(timeout?-?System.nanoTime(),?TimeUnit.NANOSECONDS);
????}
????void?print()?{
????????System.out.println(orderId?+?"編號的訂單要?jiǎng)h除啦。。。。");
????}
}
public?class?DelayQueueDemo
{
????public?static?void?main(String[]?args)
????{
????????//?TODO?Auto-generated?method?stub??
????????List??list?=?new?ArrayList??();
????????list.add("00000001");
????????list.add("00000002");
????????list.add("00000003");
????????list.add("00000004");
????????list.add("00000005");
????????DelayQueue??queue?=?newDelayQueue??();
????????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編號的訂單要?jiǎng)h除啦。。。。
After?3003?MilliSeconds
00000002編號的訂單要?jiǎng)h除啦。。。。
After?6006?MilliSeconds
00000003編號的訂單要?jiǎng)h除啦。。。。
After?9006?MilliSeconds
00000004編號的訂單要?jiǎng)h除啦。。。。
After?12008?MilliSeconds
00000005編號的訂單要?jiǎng)h除啦。。。。
After?15009?MilliSeconds
優(yōu)缺點(diǎn)
效率高,任務(wù)觸發(fā)時(shí)間延遲低。
服務(wù)器重啟后,數(shù)據(jù)全部消失,怕宕機(jī) 集群擴(kuò)展相當(dāng)麻煩 因?yàn)閮?nèi)存條件限制的原因,比如下單未付款的訂單數(shù)太多,那么很容易就出現(xiàn)OOM異常 代碼復(fù)雜度較高
(3)時(shí)間輪算法

<dependency>
????<groupId>io.nettygroupId>
????<artifactId>netty-allartifactId>
????<version>4.1.24.Finalversion>
dependency>
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("要去數(shù)據(jù)庫刪除訂單了。。。。");
????????????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秒過去了
要去數(shù)據(jù)庫刪除訂單了。。。。
6秒過去了
優(yōu)缺點(diǎn)
效率高,任務(wù)觸發(fā)時(shí)間延遲時(shí)間比delayQueue低,代碼復(fù)雜度比delayQueue低。
服務(wù)器重啟后,數(shù)據(jù)全部消失,怕宕機(jī) 集群擴(kuò)展相當(dāng)麻煩 因?yàn)閮?nèi)存條件限制的原因,比如下單未付款的訂單數(shù)太多,那么很容易就出現(xiàn)OOM異常
(4) redis緩存
添加元素: ZADD key score member [[score member] [score member] …]按順序查詢元素: ZRANGE key start stop [WITHSCORES]查詢元素: score:ZSCORE key member移除元素: ZREM key member [member …]
#?添加單個(gè)元素
redis>?ZADD?page_rank?10?google.com
(integer)?1
#?添加多個(gè)元素
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"
#?移除單個(gè)元素
?
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"

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();
??}
??//生產(chǎn)者,生成5個(gè)訂單放進(jìn)去
?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生成了一個(gè)訂單任務(wù):訂單ID為"?+?"OID0000001"?+?i);
???}
??}
??//消費(fèi)者,取訂單
?public?void?consumerDelayMessage()
?{
??Jedis?jedis?=?AppTest.getJedis();
??while(true)
??{
???Set??items?=?jedis.zrangeWithScores("OrderId",?0,?1);
???if(items?==?null?||?items.isEmpty())
???{
????System.out.println("當(dāng)前沒有等待的任務(wù)");
????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消費(fèi)了一個(gè)任務(wù):消費(fèi)的訂單OrderId為"?+?orderId);
???}
??}
?}
?public?static?void?main(String[]?args)
?{
??AppTest?appTest?=?new?AppTest();
??appTest.productionDelayMessage();
??appTest.consumerDelayMessage();
?}
}

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???{
???new?Thread(new?DelayMessage()).start();
???cdl.countDown();
??}
?}
}
if(nowSecond?>=?score)
{
?String?orderId?=?((Tuple)?items.toArray()[0]).getElement();
?jedis.zrem("OrderId",?orderId);
?System.out.println(System.currentTimeMillis()?+?"ms:redis消費(fèi)了一個(gè)任務(wù):消費(fèi)的訂單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消費(fèi)了一個(gè)任務(wù):消費(fèi)的訂單OrderId為"?+?orderId);
?}
}
notify-keyspace-events?Ex
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
?{?'http://www.jobbole.com/members/wx610506454'?>?@Override?/a>
??public?void?onMessage(String?channel,?String?message)
??{
???System.out.println(System.currentTimeMillis()?+?"ms:"?+?message?+?"訂單取消");
??}
?}
}

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的發(fā)布/訂閱目前是即發(fā)即棄(fire and forget)模式的,因此無法實(shí)現(xiàn)事件的可靠通知。也就是說,如果發(fā)布/訂閱的客戶端斷鏈之后又重連,則在客戶端斷鏈期間的所有事件都丟失了。
優(yōu)缺點(diǎn)
由于使用Redis作為消息通道,消息都存儲在Redis中。如果發(fā)送程序或者任務(wù)處理程序掛了,重啟之后,還有重新處理數(shù)據(jù)的可能性。 做集群擴(kuò)展相當(dāng)方便 時(shí)間準(zhǔn)確度高
需要額外進(jìn)行redis維護(hù)
(5)使用消息隊(duì)列
x-message-tt,來控制消息的生存時(shí)間,如果超時(shí),則消息變?yōu)?/span>dead letterx-dead-letter-exchange?和x-dead-letter-routing-key(可選)兩個(gè)參數(shù),用來控制隊(duì)列內(nèi)出現(xiàn)了deadletter,則按照這兩個(gè)參數(shù)重新路由。優(yōu)缺點(diǎn)
高效,可以利用rabbitmq的分布式特性輕易的進(jìn)行橫向擴(kuò)展,消息支持持久化增加了可靠性。
怎么接私活?這個(gè)渠道你100%有用!請收藏!
喜歡文章,點(diǎn)個(gè)在看?
評論
圖片
表情


