亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot執(zhí)行延時任務之DelayQueue的使用詳解

 更新時間:2019年12月12日 12:44:49   作者:依天照海  
DelayQueue是一個無界阻塞隊列,只有在延遲期滿時,才能從中提取元素。這篇文章主要介紹了springboot執(zhí)行延時任務-DelayQueue的使用,需要的朋友可以參考下

DelayQueue簡介

DelayQueue是一個無界阻塞隊列,只有在延遲期滿時,才能從中提取元素。
隊列的頭部,是延遲期滿后保存時間最長的delay元素。

在很多場景我們需要用到延時任務,比如給客戶異步轉賬操作超時后發(fā)通知告知用戶,還有客戶下單后多長時間內(nèi)沒支付則取消訂單等等,這些都可以使用延時任務來實現(xiàn)。

jdk中DelayQueue可以實現(xiàn)上述需求,顧名思義DelayQueue就是延時隊列。

DelayQueue提供了在指定時間才能獲取隊列元素的功能,隊列頭元素是最接近過期的元素。

沒有過期元素的話,使用poll()方法會返回null值,超時判定是通過getDelay(TimeUnit.NANOSECONDS)方法的返回值小于等于0來判斷。

延時隊列不能存放空元素。

一般使用take()方法阻塞等待,有過期元素時繼續(xù)。

隊列元素說明

DelayQueue<E extends Delayed>的隊列元素需要實現(xiàn)Delayed接口,該接口類定義如下:

public interface Delayed extends Comparable<Delayed> {

 /**
  * Returns the remaining delay associated with this object, in the
  * given time unit.
  *
  * @param unit the time unit
  * @return the remaining delay; zero or negative values indicate
  * that the delay has already elapsed
  */
 long getDelay(TimeUnit unit);
}

所以DelayQueue的元素需要實現(xiàn)getDelay方法和Comparable接口的compareTo方法,getDelay方法來判定元素是否過期,compareTo方法來確定先后順序。

springboot中實例運用

DelayTask就是隊列中的元素

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class DelayTask implements Delayed {
 final private TaskBase data;
 final private long expire;
 /**
  * 構造延時任務
  * @param data  業(yè)務數(shù)據(jù)
  * @param expire 任務延時時間(ms)
  */
 public DelayTask(TaskBase data, long expire) {
  super();
  this.data = data;
  this.expire = expire + System.currentTimeMillis();
 }
 public TaskBase getData() {
  return data;
 }
 public long getExpire() {
  return expire;
 }
 @Override
 public boolean equals(Object obj) {
  if (obj instanceof DelayTask) {
   return this.data.getIdentifier().equals(((DelayTask) obj).getData().getIdentifier());
  }
  return false;
 }
 @Override
 public String toString() {
  return "{" + "data:" + data.toString() + "," + "expire:" + new Date(expire) + "}";
 }
 @Override
 public long getDelay(TimeUnit unit) {
  return unit.convert(this.expire - System.currentTimeMillis(), unit);
 }
 @Override
 public int compareTo(Delayed o) {
  long delta = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
  return (int) delta;
 }
}

TaskBase類是用戶自定義的業(yè)務數(shù)據(jù)基類,其中有一個identifier字段來標識任務的id,方便進行索引

import com.alibaba.fastjson.JSON;
public class TaskBase {
 private String identifier;
 public TaskBase(String identifier) {
  this.identifier = identifier;
 }
 public String getIdentifier() {
  return identifier;
 }
 public void setIdentifier(String identifier) {
  this.identifier = identifier;
 }
 @Override
 public String toString() {
  return JSON.toJSONString(this);
 }
}

定義一個延時任務管理類DelayQueueManager,通過@Component注解加入到spring中管理,在需要使用的地方通過@Autowire注入

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;
@Component
public class DelayQueueManager implements CommandLineRunner {
 private final Logger logger = LoggerFactory.getLogger(DelayQueueManager.class);
 private DelayQueue<DelayTask> delayQueue = new DelayQueue<>();
 /**
  * 加入到延時隊列中
  * @param task
  */
 public void put(DelayTask task) {
  logger.info("加入延時任務:{}", task);
  delayQueue.put(task);
 }
 /**
  * 取消延時任務
  * @param task
  * @return
  */
 public boolean remove(DelayTask task) {
  logger.info("取消延時任務:{}", task);
  return delayQueue.remove(task);
 }
 /**
  * 取消延時任務
  * @param taskid
  * @return
  */
 public boolean remove(String taskid) {
  return remove(new DelayTask(new TaskBase(taskid), 0));
 }
 @Override
 public void run(String... args) throws Exception {
  logger.info("初始化延時隊列");
  Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
 }
 /**
  * 延時任務執(zhí)行線程
  */
 private void excuteThread() {
  while (true) {
   try {
    DelayTask task = delayQueue.take();
    processTask(task);
   } catch (InterruptedException e) {
    break;
   }
  }
 }
 /**
  * 內(nèi)部執(zhí)行延時任務
  * @param task
  */
 private void processTask(DelayTask task) {
  logger.info("執(zhí)行延時任務:{}", task);
  //根據(jù)task中的data自定義數(shù)據(jù)來處理相關邏輯,例 if (task.getData() instanceof XXX) {}
 }
}

DelayQueueManager實現(xiàn)了CommandLineRunner接口,在springboot啟動完成后就會自動調(diào)用run方法。

總結

以上所述是小編給大家介紹的springboot執(zhí)行延時任務DelayQueue的使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!

相關文章

  • Java 如何實現(xiàn)時間控制

    Java 如何實現(xiàn)時間控制

    這篇文章主要向大家介紹得是Java 如何實現(xiàn)時間控制,文章珠岙舉例說明該內(nèi)容,感興趣得小伙伴可以跟小編一起學習下面文章內(nèi)容
    2021-10-10
  • 使用springboot訪問圖片本地路徑并映射成url

    使用springboot訪問圖片本地路徑并映射成url

    這篇文章主要介紹了使用springboot訪問圖片本地路徑并映射成url的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java并發(fā)編程信號量Semapher

    Java并發(fā)編程信號量Semapher

    這篇文章主要介紹了Java并發(fā)編程信號量Semapher,Semapher信號量也是Java中的一個同步器,下文關于信號量Semapher的更多內(nèi)容介紹,需要的小伙伴可以參考下面文章
    2022-04-04
  • IDEA配置tomcat的方法、IDEA配置tomcat運行web項目詳解

    IDEA配置tomcat的方法、IDEA配置tomcat運行web項目詳解

    這篇文章主要介紹了IDEA配置tomcat的方法、IDEA配置tomcat運行web項目詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Mybatis分頁的實現(xiàn)及使用注解開發(fā)操作

    Mybatis分頁的實現(xiàn)及使用注解開發(fā)操作

    這篇文章主要介紹了Mybatis分頁的實現(xiàn)及使用注解開發(fā)操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Java 實現(xiàn)滑動時間窗口限流算法的代碼

    Java 實現(xiàn)滑動時間窗口限流算法的代碼

    這篇文章主要介紹了Java 實現(xiàn)滑動時間窗口限流算法的代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • java中equals和等號(==)的區(qū)別淺談

    java中equals和等號(==)的區(qū)別淺談

    java中equals和等號(==)的區(qū)別淺談,需要的朋友可以參考一下
    2013-05-05
  • JAVA如何調(diào)用Shell腳本

    JAVA如何調(diào)用Shell腳本

    本篇文章主要介紹了JAVA如何調(diào)用Shell腳本,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • 淺談Java并發(fā)編程之Lock鎖和條件變量

    淺談Java并發(fā)編程之Lock鎖和條件變量

    這篇文章主要介紹了淺談Java并發(fā)編程之Lock鎖和條件變量,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-08-08
  • 關于SpringBoot的自動裝配原理詳解

    關于SpringBoot的自動裝配原理詳解

    這篇文章主要介紹了關于SpringBoot的自動裝配原理詳解,Spring?Boot自動裝配原理是指Spring?Boot在啟動時自動掃描項目中的依賴關系,根據(jù)依賴關系自動配置相應的Bean,從而簡化了Spring應用的配置過程,需要的朋友可以參考下
    2023-07-07

最新評論