Spring Boot + Redis 实现延迟队列
在Spring Boot中,你可以使用@EnableScheduling
注解来创建一个简单的延迟队列。以下是一个使用Redis作为延迟存储和调度的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 在Spring Boot应用的主类或配置类上添加
@EnableScheduling
注解:
@SpringBootApplication
@EnableScheduling
public class DelayQueueApplication {
public static void main(String[] args) {
SpringApplication.run(DelayQueueApplication.class, args);
}
}
- 创建一个延迟队列的任务:
@Component
public class DelayQueueTask {
private static final Logger LOGGER = LoggerFactory.getLogger(DelayQueueTask.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Scheduled(fixedRate = 5000)
public void processDelayQueue() {
List<String> keys = stringRedisTemplate.keys("delay_queue:*");
for (String key : keys) {
Long delay = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
if (delay != null && delay > 0) {
// 任务还没有到期,继续等待
continue;
}
// 获取任务并处理
String task = stringRedisTemplate.opsForValue().get(key);
if (task != null) {
LOGGER.info("Processing task: {}", task);
// 处理任务的逻辑
// ...
// 处理完毕后删除任务
stringRedisTemplate.delete(key);
}
}
}
public void enqueueTask(String taskId, long delaySeconds) {
stringRedisTemplate.opsForValue().set("delay_queue:" + taskId, "task_data",
Duration.ofSeconds(delaySeconds));
}
}
- 使用
enqueueTask
方法向延迟队列中添加任务:
@RestController
public class DelayQueueController {
@Autowired
private DelayQueueTask delayQueueTask;
@PostMapping("/enqueue")
public String enqueueTask(@RequestParam String taskId, @RequestParam long delaySeconds) {
delayQueueTask.enqueueTask(taskId, delaySeconds);
评论已关闭