下面是一个使用 Spring Boot 编写的 Redis 任务队列的示例代码:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
public class RedisTaskQueueApplication {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static void main(String[] args) {
        SpringApplication.run(RedisTaskQueueApplication.class, args);
    }

    @Scheduled(fixedDelay = 1000) // 每隔1秒执行一次任务
    public void processTaskQueue() {
        String task = redisTemplate.opsForList().rightPop('taskQueue'); // 从队列右侧取出任务
        if (task != null) {
            // 执行任务逻辑
            System.out.println('Processing task: ' + task);
        }
    }
}

在上述代码中,通过注解 @SpringBootApplication@EnableScheduling 启用 Spring Boot 和定时任务功能。使用 @Autowired 注入了一个 RedisTemplate 实例,用于操作 Redis。在 processTaskQueue 方法中,通过 redisTemplate.opsForList().rightPop('taskQueue') 从名为 taskQueue 的 Redis 列表中取出任务,如果列表不为空,则执行相应的任务逻辑。可以根据实际需求,调整定时任务的执行频率和任务逻辑。

需要注意的是,该示例代码仅完成了从 Redis 队列中取出任务的逻辑,具体的任务处理逻辑需要根据实际需求自行编写。

Spring Boot Redis 任务队列实战:代码示例及解析

原文地址: https://www.cveoy.top/t/topic/ph2u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录