• 9.3.2. 任务

    9.3.2. 任务

    Redisson独立节点不要求任务的类在类路径里。他们会自动被Redisson独立节点的ClassLoader加载。因此每次执行一个新任务时,不需要重启Redisson独立节点。

    采用Callable任务的范例:

    1. public class CallableTask implements Callable<Long> {
    2. @RInject
    3. private RedissonClient redissonClient;
    4. @Override
    5. public Long call() throws Exception {
    6. RMap<String, Integer> map = redissonClient.getMap("myMap");
    7. Long result = 0;
    8. for (Integer value : map.values()) {
    9. result += value;
    10. }
    11. return result;
    12. }
    13. }

    采用Runnable任务的范例:

    1. public class RunnableTask implements Runnable {
    2. @RInject
    3. private RedissonClient redissonClient;
    4. private long param;
    5. public RunnableTask() {
    6. }
    7. public RunnableTask(long param) {
    8. this.param = param;
    9. }
    10. @Override
    11. public void run() {
    12. RAtomicLong atomic = redissonClient.getAtomicLong("myAtomic");
    13. atomic.addAndGet(param);
    14. }
    15. }

    在创建ExecutorService时可以配置以下参数:

    1. ExecutorOptions options = ExecutorOptions.defaults()
    2. // 指定重新尝试执行任务的时间间隔。
    3. // ExecutorService的工作节点将等待10分钟后重新尝试执行任务
    4. //
    5. // 设定为0则不进行重试
    6. //
    7. // 默认值为5分钟
    8. options.taskRetryInterval(10, TimeUnit.MINUTES);
    1. RExecutorService executorService = redisson.getExecutorService("myExecutor", options);
    2. executorService.submit(new RunnableTask(123));
    3. RExecutorService executorService = redisson.getExecutorService("myExecutor", options);
    4. Future<Long> future = executorService.submit(new CallableTask());
    5. Long result = future.get();

    使用Lambda任务的范例:

    1. RExecutorService executorService = redisson.getExecutorService("myExecutor", options);
    2. Future<Long> future = executorService.submit((Callable & Serializable)() -> {
    3. System.out.println("task has been executed!");
    4. });
    5. Long result = future.get();

    可以通过@RInject注解来为任务实时注入Redisson实例依赖。