Java 延遲隊(duì)列的常用的實(shí)現(xiàn)方式
延遲隊(duì)列的使用場景還比較多,例如:
1、超時(shí)未收到支付回調(diào),主動(dòng)查詢支付狀態(tài);
2、規(guī)定時(shí)間內(nèi),訂單未支付,自動(dòng)取消;
。。。
總之,但凡需要在未來的某個(gè)確定的時(shí)間點(diǎn)執(zhí)行檢查的場景中都可以用延遲隊(duì)列。
常見的手段主要有:定時(shí)任務(wù)掃描、RocketMQ延遲隊(duì)列、Java自動(dòng)的延遲隊(duì)列、監(jiān)聽Redis Key過期等等
1. DelayQueue
首先,定義一個(gè)延遲任務(wù)
package com.cjs.example;
import lombok.Data;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* @author ChengJianSheng
* @since 2021/3/18
*/
@Data
public class DelayTask implements Delayed {
private Long orderId;
private long expireTime;
public DelayTask(Long orderId, long expireTime) {
this.orderId = orderId;
this.expireTime = expireTime;
}
@Override
public long getDelay(TimeUnit unit) {
return expireTime - System.currentTimeMillis();
}
@Override
public int compareTo(Delayed o) {
return (int) (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
}
}
然后,定義一個(gè)管理類
package com.cjs.example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author ChengJianSheng
* @since 2021/3/19
*/
@Slf4j
@Component
public class DelayQueueManager implements CommandLineRunner {
private DelayQueue<DelayTask> queue = new DelayQueue<>();
@Autowired
private ParkOrderQueryHandler handler;
@Override
public void run(String... strings) throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
while (true) {
try {
DelayTask task = queue.take();
handler.handle(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public void put(DelayTask task) {
queue.put(task);
}
}
插入任務(wù)
@Slf4j
@Service
public class PayServiceImpl implements PayService {
@Autowired
private DelayQueueManager delayQueueManager;
@Override
public void pay() {
delayQueueManager.put(new DelayTask(1, 15));
delayQueueManager.put(new DelayTask(2, 30));
delayQueueManager.put(new DelayTask(3, 60));
}
}
2. Redis Key過期回調(diào)
修改redis.conf文件
# bind 127.0.0.1 -::1
protected-mode no
notify-keyspace-events Ex

[root@localhost redis-6.2.1]$ src/redis-server redis.conf
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo0401</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo0401</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
RedisConfig.java
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
* @author ChengJianSheng
* @since 2021/4/2
*/
@Configuration
public class RedisConfig {
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
創(chuàng)建一個(gè)監(jiān)聽類
package com.example.listener;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
/**
* @author ChengJianSheng
* @since 2021/4/2
*/
@Component
public class MyRedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public MyRedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
System.out.println("監(jiān)聽到Key: " + expiredKey + " 已過期");
}
}
3. RocketMQ

官方文檔:https://help.aliyun.com/document_detail/29549.htm
以上就是Java 延遲隊(duì)列的常用的實(shí)現(xiàn)方式的詳細(xì)內(nèi)容,更多關(guān)于Java 延遲隊(duì)列實(shí)現(xiàn)方式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java異常:異常處理--try-catch結(jié)構(gòu)詳解
今天小編就為大家分享一篇關(guān)于Java異常處理之try...catch...finally詳解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2021-09-09
SpringBoot常用數(shù)據(jù)庫開發(fā)技術(shù)匯總介紹
Spring Boot常用的數(shù)據(jù)庫開發(fā)技術(shù)有JDBCTemplate、JPA和Mybatis,它們分別具有不同的特點(diǎn)和適用場景,可以根據(jù)具體的需求選擇合適的技術(shù)來進(jìn)行開發(fā)2023-04-04
關(guān)于Java兩個(gè)浮點(diǎn)型數(shù)字加減乘除的問題
由于浮點(diǎn)數(shù)在計(jì)算機(jī)中是以二進(jìn)制表示的,直接進(jìn)行加減乘除運(yùn)算會(huì)出現(xiàn)精度誤差,想要得到精確結(jié)果,應(yīng)使用BigDecimal類進(jìn)行運(yùn)算2024-10-10
Java參數(shù)校驗(yàn)@Validated、@Valid介紹及使用詳解
Javax.validation是?spring?集成自帶的一個(gè)參數(shù)校驗(yàn)接口,可通過添加注解來設(shè)置校驗(yàn)條件,這篇文章主要介紹了Java參數(shù)校驗(yàn)@Validated、@Valid介紹及使用詳解,需要的朋友可以參考下2024-08-08
JAVA8 STREAM COLLECT GROUPBY分組實(shí)例解析
這篇文章主要介紹了JAVA8 STREAM COLLECT GROUPBY分組實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
Spring如何配置文件動(dòng)態(tài)讀取pom.xml中的屬性
在項(xiàng)目開發(fā)中,經(jīng)常需要將pom.xml中的屬性動(dòng)態(tài)傳遞給Spring配置文件,實(shí)現(xiàn)這一需求,可通過Maven的資源過濾功能,配置占位符替換,具體方法包括:在pom.xml中啟用filtering,然后在Spring配置文件中通過${property}方式引用屬性2024-10-10

