我已经使用redisson创建了一个调度器,它在正常情况下工作。但是如果服务重新启动,调度程序不会被触发,这就是我首先使用redison调度的原因。当我检查redis数据网格时,redis中有与调度器相关的信息。
是否需要进行任何特定的配置以启用持久的调度。
再贴现配置
@Configuration
public class RedisConfiguration {
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.host}")
private String redisHost;
@Bean
RedissonConnectionFactory redissonConnectionFactory(RedissonClient redissonClient) {
return new RedissonConnectionFactory(redissonClient);
}
@Bean(destroyMethod = "shutdown")
RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress("redis://" + redisHost + ":" + redisPort);
return Redisson.create(config);
}
}
调度服务
@Service
public class SchedulerService {
private static final String SCHEDULED_TASK_ID_MAP = "SCHEDULED_TASK_ID_MAP";
private final RedissonClient redissonClient;
private final int numOfWorkers;
@Autowired
public SchedulerService(final RedissonClient redissonClient,
@Value("${app.redis.workers.count}") final int numOfWorkers) {
this.redissonClient = redissonClient;
this.numOfWorkers = numOfWorkers;
}
public String scheduleTask(final TaskInfo taskInfo) {
SchedulerTask task = SchedulerTask.builder().taskInfo(taskInfo).build();
RScheduledExecutorService executorService = redissonClient
.getExecutorService(taskInfo.getJobKey());
executorService
.registerWorkers(getWorkerOptions(getScheduledTaskIdMap(), taskInfo.getJobKey()));
RScheduledFuture<?> future = executorService
.schedule(task, taskInfo.getDelay(), taskInfo.getTimeUnit());
getScheduledTaskIdMap().put(taskInfo.getJobKey(), future.getTaskId());
return taskInfo.getJobKey();
}
public boolean cancelTask(final String jobKey) {
String taskId = getScheduledTaskIdMap().get(jobKey);
if (!StringUtils.isEmpty(taskId)) {
boolean isCancelled = cancelTask(jobKey, taskId);
if (isCancelled) {
removeTaskId(jobKey);
}
return isCancelled;
}
throw new InvalidJobKeyException("Invalid job key : " + jobKey);
}
private RMap<String, String> getScheduledTaskIdMap() {
return redissonClient.getMap(SCHEDULED_TASK_ID_MAP);
}
private boolean cancelTask(final String jobKey, final String taskId) {
RScheduledExecutorService executorService = redissonClient.getExecutorService(jobKey);
boolean isCancelled = false;
if (executorService.hasTask(taskId)) {
isCancelled = executorService.cancelTask(taskId);
}
return isCancelled;
}
private void removeTaskId(final String jobKey) {
getScheduledTaskIdMap().remove(jobKey);
}
private WorkerOptions getWorkerOptions(final RMap<String, String> rMap, final String jobKey) {
return WorkerOptions.defaults().workers(numOfWorkers)
.addListener(new TaskSuccessListenerImpl(rMap, jobKey));
}
}
依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.1</version>
</dependency>
Redis调度程序信息映像
暂无答案!
目前还没有任何答案,快来回答吧!