溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Java中使用延遲隊(duì)列

發(fā)布時(shí)間:2021-04-06 15:50:52 來(lái)源:億速云 閱讀:287 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)如何在Java中使用延遲隊(duì)列,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

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過(guò)期回調(diào)

修改redis.conf文件

# bind 127.0.0.1 -::1
protected-mode no
notify-keyspace-events Ex

如何在Java中使用延遲隊(duì)列

[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)聽(tīng)類

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)聽(tīng)到Key: " + expiredKey + " 已過(guò)期");
 }
}

3.  RocketMQ

如何在Java中使用延遲隊(duì)列

以上就是如何在Java中使用延遲隊(duì)列,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI