在springboot中利用Redis实现延迟队列
在Spring Boot中,你可以使用Spring Data Redis
和Redis
的zset
(有序集合)来实现延迟队列。以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置RedisTemplate:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
final RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
}
- 创建一个服务来操作Redis的zset:
@Service
public class DelayQueueService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void enqueue(Object item, long delaySeconds) {
long score = System.currentTimeMillis() / 1000 + delaySeconds;
redisTemplate.opsForZSet().add("delay_queue", item, score);
}
public Object dequeue() {
Set<Object> items = redisTemplate.opsForZSet().rangeByScore("delay_queue", 0, System.currentTimeMillis() / 1000);
if (items != null && !items.isEmpty()) {
Object item = items.iterator().next();
redisTemplate.opsForZSet().remove("delay_queue", item);
return item;
}
return null;
}
}
- 使用这个服务来添加和处理延迟队列中的任务:
@RestController
public class DelayQueueController {
@Autowired
private DelayQueueService delayQueueService;
@GetMapping("/enqueue")
public String enqueue(@RequestParam String data, @RequestParam long delaySeconds) {
delayQueueService.enqueue(data, delaySeconds);
return "Item added to the delay queue";
}
@Scheduled(fixedRate = 1000)
public void processDelayQueue() {
Object item = delayQueueService.dequeue();
if (item != null) {
// 处理任务
System.out.println("Processing item: " + item);
}
}
}
确保你的Spring Boot应用程序开启了定时任务:
@EnableScheduling
@SpringBootApplication
public class DelayQueueApplication {
public static void main(String[] args) {
SpringApplication.run(DelayQueueApplication.class, args);
}
}
在这个例子中,DelayQueueService
提供了enqueue
方法来将任务添加到Redis的zset中,并设置了何时才能从队列中取出它。processDelayQueue
方法是一个定时任务,它会检查并处理那些到期的任务。这个实
评论已关闭