我希望在我们的项目中取代Quartz作为作业调度器。我们已经使用支持集群的Redis作为分布式缓存层,我们想也许我们也可以使用Redis来进行作业调度。有没有人用Redis在Java中实现了作业调度?我搜索了一下,但找不到用于此目的的库。所以我开始认为这可能不是一个流行的解决方案?
发布于 2016-08-25 02:29:48
看看Redisson吧。它允许使用简单的Redis api和基于Redis queue的ScheduledExecutorService调度和执行任务(支持cron表达式)。
下面是一个例子。首先使用java.lang.Runnable接口定义一个任务。每个任务都可以通过注入的RedissonClient对象访问Redis实例。
public class RunnableTask implements Runnable {
@RInject
private RedissonClient redissonClient;
@Override
public void run() throws Exception {
RMap<String, Integer> map = redissonClient.getMap("myMap");
Long result = 0;
for (Integer value : map.values()) {
result += value;
}
redissonClient.getTopic("myMapTopic").publish(result);
}
}提交给基于Redis的ExecutorService
RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
RScheduledFuture<?> future = executorService.schedule(new CallableTask(), 10, 20, TimeUnit.MINUTES);
future.get();
// or cancel it
future.cancel(true);
// cancel by taskId
executorService.cancelTask(future.getTaskId());使用cron表达式的示例:
executorService.schedule(new RunnableTask(), CronSchedule.of("10 0/5 * * * ?"));
executorService.schedule(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));
executorService.schedule(new RunnableTask(), CronSchedule.weeklyOnDayAndHourAndMinute(12, 4, Calendar.MONDAY, Calendar.FRIDAY));所有任务都分布在Redisson nodes上。您可以根据需要运行这些节点。
发布于 2016-03-25 23:38:41
发布于 2021-04-09 23:22:48
我将Spring Task Scheduler与Shedlock和Redis结合使用,以使预定任务的执行具有可分布性。
在我的XML配置文件中,我指定了任务调度程序:
<task:scheduler id="myScheduler" pool-size="4"/>
<task:annotation-driven scheduler="myScheduler" />在SchedulerLockConfiguration.java中,我创建了Redis Spring bean,并设置了LockProvider连接和Jedis连接池:
@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT10H")
public class SchedulerLockConfiguration {
@Bean
public JedisPool jedisPool() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(100); // The maximum number of connections that are supported by the pool
jedisPoolConfig.setMaxIdle(100); // The maximum number of idle connections in the pool
jedisPoolConfig.setMinIdle(10); // The minimum number of idle connections in the pool
return new JedisPool(
jedisPoolConfig,
Constants.REDIS_HOSTNAME,
Integer.parseInt(Constants.REDIS_PORT),
Integer.parseInt(Constants.REDIS_SESSION_TIMEOUT),
null,
Constants.REDIS_DATABASE_SHEDLOCK);
}
@Bean
public LockProvider lockProvider(JedisPool jedisPool) {
return new JedisLockProvider(jedisPool, "yourRedisNamespace");
}
}最后,我在要调度的方法上使用了@Scheduled和@SchedulerLock注释:
@Scheduled(cron = "${my.cron.expression}")
@SchedulerLock(name = "myScheduler", lockAtLeastFor = "PT10M")
public void processDelayedAutomationRules() { ... }当@Scheduled作业的cron生效时,哪个应用程序实例/服务器节点将锁更快地放入Redis存储中,就是哪个应用程序实例/服务器节点执行它。
https://stackoverflow.com/questions/36221606
复制相似问题