1.maven配置
<!-- 用于管理起步工程的依赖管理 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.11</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.10.6</version>
</dependency>
</dependencies>
2.yml配置
server:
port: 9007
servlet:
context-path: /
spring:
redis:
# 超时时间
timeout: 10000ms
# 服务器地址
host: 127.0.0.1
# 服务器端口
port: 6379
# 数据库
database: 0
# 密码
password: 123456
lettuce:
pool:
# 最大连接数,默认8
max-active: 1024
# 最大连接阻塞等待时间,默认-1
max-wait: 10000ms
# 最大空闲连接
max-idle: 200
# 最小空闲连接
min-idle: 5
3.config
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
public class RedissonConfig {
@Bean(destroyMethod = "shutdown")
public RedissonClient redissonClient(RedisProperties redisProperties){
Config config = new Config();
SingleServerConfig singleServerConfig = config.useSingleServer();
singleServerConfig.setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort());
singleServerConfig.setPassword(redisProperties.getPassword());
singleServerConfig.setKeepAlive(true);
// 根据config创建出RedissonClient实例
RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
}
}
4.service
public void delayed() throws InterruptedException {
// 阻塞队列:RBlockingDeque的实现类为:new RedissonBlockingDeque
RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("delayedQueue");
// 获取延迟队列
RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "添加任务到延时队列里面");
// 添加延迟任务
delayedQueue.offer( "task1第一个任务", 6, TimeUnit.SECONDS);
delayedQueue.offer( "task2第二个任务", 4, TimeUnit.SECONDS);
System.out.println("--------------------Begin");
// 通过 take 方法等待并获取到期的任务
while (true) {
String task = blockingDeque.take();
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "延时队列收到:" + task);
}
}
5.结果
![](https://i-blog.csdnimg.cn/blog_migrate/a54fc4277af1ecfa1debe73668aed940.png)