9.1. Remote service

Redisson provides Java Remote Services to execute remote procedure call using Redis. Remote interface could have any type of method parameters and result object. Redis is used to store method request and corresponding execution result.

The RemoteService provides two types of RRemoteService instances:

  • Server side instance - executes remote method (worker instance). Example: ```java RRemoteService remoteService = redisson.getRemoteService(); SomeServiceImpl someServiceImpl = new SomeServiceImpl();

// register remote service before any remote invocation // can handle only 1 invocation concurrently remoteService.register(SomeServiceInterface.class, someServiceImpl);

// register remote service able to handle up to 12 invocations concurrently remoteService.register(SomeServiceInterface.class, someServiceImpl, 12);

  1. * __Client side instance__ - invokes remote method.
  2. Example:
  3. ```java
  4. RRemoteService remoteService = redisson.getRemoteService();
  5. SomeServiceInterface service = remoteService.get(SomeServiceInterface.class);
  6. String result = service.doSomeStuff(1L, "secondParam", new AnyParam());

Client and server side instances shall be using the same remote interface and backed by redisson instances created using the same server connection configuration. Client and server side instances could be run in same JVM. There are no limits to the amount of client and/or server instances. (Note: While redisson does not enforce any limits, limitations from Redis still apply.)

Remote invocations executes in parallel mode if 1+ workers are available.

9. Distributed services - 图1

The total number of parallel executors is calculated as such: T = R * N

T - total available parallel executors R - Redisson server side instance amount N - executors amount defined during service registration

Commands exceeding this number will be queued for the next available executor.

Remote invocations executes in sequential mode if only 1 workers are available. Only one command can be handled concurrently in this case and the rest of commands will be queued.

9. Distributed services - 图2

9.1.1. Remote service. Message flow

RemoteService creates two queues per invocation. One queue for request (being listened by server side instance) and another one is for ack-response and result-response (being listened by client side instance). Ack-response used to determine if method executor has got a request. If it doesn’t during ack timeout then RemoteServiceAckTimeoutException will be thrown.

Below is depicted a message flow for each remote invocation.

9. Distributed services - 图3

9.1.2. Remote service. Fire-and-forget and ack-response modes

RemoteService options for each remote invocation could be defined via RemoteInvocationOptions object. Such options allow to change timeouts and skip ack-response and/or result-response. Examples:

  1. // 1 second ack timeout and 30 seconds execution timeout
  2. RemoteInvocationOptions options = RemoteInvocationOptions.defaults();
  3. // no ack but 30 seconds execution timeout
  4. RemoteInvocationOptions options = RemoteInvocationOptions.defaults().noAck();
  5. // 1 second ack timeout then forget the result
  6. RemoteInvocationOptions options = RemoteInvocationOptions.defaults().noResult();
  7. // 1 minute ack timeout then forget about the result
  8. RemoteInvocationOptions options = RemoteInvocationOptions.defaults().expectAckWithin(1, TimeUnit.MINUTES).noResult();
  9. // no ack and forget about the result (fire and forget)
  10. RemoteInvocationOptions options = RemoteInvocationOptions.defaults().noAck().noResult();
  11. RRemoteService remoteService = redisson.getRemoteService();
  12. YourService service = remoteService.get(YourService.class, options);

9.1.3. Remote service. Asynchronous, Reactive and RxJava3 calls

Remote method could be executed using Async, Reactive and RxJava3 Api.

Asynchronous Remote interface. Interface should be annotated with @RRemoteAsync. Method signatures match with the methods in remote interface and return RFuture object.

Reactive Remote interface. Interface should be annotated with @RRemoteReactive. Method signatures match with the methods in remote interface and return reactor.core.publisher.Mono object.

RxJava3 Remote interface. Interface should be annotated with @RRemoteRx. Method signatures match with the methods in remote interface and return one of the following object: io.reactivex.Completable, io.reactivex.Single, io.reactivex.Maybe.

It’s not necessary to list all methods, only those which are needed. Below is an example of Remote Service interface:

  1. public interface RemoteInterface {
  2. Long someMethod1(Long param1, String param2);
  3. void someMethod2(MyObject param);
  4. MyObject someMethod3();
  5. }

Asynchronous Remote interface and method call example:

  1. @RRemoteAsync(RemoteInterface.class)
  2. public interface RemoteInterfaceAsync {
  3. RFuture<Long> someMethod1(Long param1, String param2);
  4. RFuture<Void> someMethod2(MyObject param);
  5. }
  6. RedissonClient redisson = Redisson.create(config);
  7. RRemoteService remoteService = redisson.getRemoteService();
  8. RemoteInterfaceAsync asyncService = remoteService.get(RemoteInterfaceAsync.class);
  9. asyncService.someMethod1(1L, "myparam");

Reactive Remote interface and method call example:

  1. @RRemoteReactive(RemoteInterface.class)
  2. public interface RemoteInterfaceReactive {
  3. Mono<Long> someMethod1(Long param1, String param2);
  4. Mono<Void> someMethod2(MyObject param);
  5. }
  6. RedissonReactiveClient redisson = Redisson.createReactive(config);
  7. RRemoteService remoteService = redisson.getRemoteService();
  8. RemoteInterfaceReactive reactiveService = remoteService.get(RemoteInterfaceReactive.class);
  9. reactiveService.someMethod1(1L, "myparam");

RxJava3 Remote interface and method call example:

  1. @RRemoteRx(RemoteInterface.class)
  2. public interface RemoteInterfaceRx {
  3. Single<Long> someMethod1(Long param1, String param2);
  4. Completable someMethod2(MyObject param);
  5. }
  6. RedissonRxClient redisson = Redisson.createRx(config);
  7. RRemoteService remoteService = redisson.getRemoteService();
  8. RemoteInterfaceReactive rxService = remoteService.get(RemoteInterfaceRx.class);
  9. rxService.someMethod1(1L, "myparam");

9.1.4. Remote service. Asynchronous, Reactive and RxJava3 call cancellation

Remote service provides ability to cancel invocation in any stages of its execution. There are three stages:

  1. Remote invocation request in queue
  2. Remote invocation request received by remote service but not lunched and Ack-response hasn’t send yet
  3. Remote invocation execution in progress

To handle third stage you need to check for Thread.currentThread().isInterrupted() status in your Remote service code. Here is an example:

  1. public interface MyRemoteInterface {
  2. Long myBusyMethod(Long param1, String param2);
  3. }
  4. @RRemoteAsync(MyRemoteInterface.class)
  5. public interface MyRemoteInterfaceAsync {
  6. RFuture<Long> myBusyMethod(Long param1, String param2);
  7. }
  8. @RRemoteReactive(MyRemoteInterface.class)
  9. public interface MyRemoteInterfaceReactive {
  10. Mono<Long> myBusyMethod(Long param1, String param2);
  11. }
  12. @RRemoteRx(MyRemoteInterface.class)
  13. public interface MyRemoteInterfaceRx {
  14. Single<Long> myBusyMethod(Long param1, String param2);
  15. }
  16. // remote service implementation
  17. public class MyRemoteServiceImpl implements MyRemoteInterface {
  18. public Long myBusyMethod(Long param1, String param2) {
  19. for (long i = 0; i < Long.MAX_VALUE; i++) {
  20. iterations.incrementAndGet();
  21. if (Thread.currentThread().isInterrupted()) {
  22. System.out.println("interrupted! " + i);
  23. return;
  24. }
  25. }
  26. }
  27. }
  28. RRemoteService remoteService = redisson.getRemoteService();
  29. ExecutorService executor = Executors.newFixedThreadPool(5);
  30. // register remote service using separate
  31. // ExecutorService used to execute remote invocation
  32. MyRemoteInterface serviceImpl = new MyRemoteServiceImpl();
  33. remoteService.register(MyRemoteInterface.class, serviceImpl, 5, executor);
  34. // call Asynchronous method
  35. MyRemoteInterfaceAsync asyncService = remoteService.get(MyRemoteInterfaceAsync.class);
  36. RFuture<Long> future = asyncService.myBusyMethod(1L, "someparam");
  37. // cancel invocation
  38. future.cancel(true);
  39. // call Reactive method
  40. MyRemoteInterfaceReactive reactiveService = remoteService.get(MyRemoteInterfaceReactive.class);
  41. Mono<Long> mono = reactiveService.myBusyMethod(1L, "someparam");
  42. Disposable disp = mono.doOnSubscribe(s -> s.request(1)).subscribe();
  43. // cancel invocation
  44. disp.dispose();
  45. // call RxJava3 method
  46. MyRemoteInterfaceRx asyncService = remoteService.get(MyRemoteInterfaceRx.class);
  47. Single<Long> single = asyncService.myBusyMethod(1L, "someparam");
  48. Disposable disp = single.subscribe();
  49. // cancel invocation
  50. disp.dispose();

9.2. Live Object service

9.2.1. Introduction

A Live Object can be understood as an enhanced version of standard Java object, of which an instance reference can be shared not only between threads in a single JVM, but can also be shared between different JVMs across different machines.Wikipedia discribes it as:

Live distributed object (also abbreviated as live object) refers to a running instance of a distributed multi-party (or peer-to-peer) protocol, viewed from the object-oriented perspective, as an entity that has a distinct identity, may encapsulate internal state and threads of execution, and that exhibits a well-defined externally visible behavior.

Redisson Live Object (RLO) realised this idea by mapping all the fields inside a Java class to a redis hash through a runtime-constructed proxy class. All the getters/setters methods of each field are translated to hget/hset commands operated on the redis hash, making it accessable to/from any clients connected to the same redis server. Getters/setters/constructors can’t be generated by byte-code tools like Lombok. Additional methods should use getters and not fields. As we all know, the field values of an object represent its state; having them stored in a remote repository, redis, makes it a distributed object. This object is a Redisson Live Object.

By using RLO, sharing an object between applications and/or servers is the same as sharing one in a standalone application. This removes the need for serialization and deserialization, and at the same time reduces the complexity of the programming model: Changes made to one field is (almost^) immediately accessable to other processes, applications and servers.

Since the redis server is a single-threaded application, all field access to the live object is automatically executed in atomic fashion: a value will not be changed when you are reading it.

With RLO, you can treat the redis server as a shared Heap space for all connected JVMs.

9.2.2. Usage

Redisson provides different annotations for Live Object. @RId and @REntity annotation are required to create and use Live Object.

  1. @REntity
  2. public class MyObject {
  3. @RId
  4. private String id;
  5. @RIndex
  6. private String value;
  7. private transient SimpleObject simpleObject;
  8. private MyObject parent;
  9. public MyObject(String id) {
  10. this.id = id;
  11. }
  12. public MyObject() {
  13. }
  14. // getters and setters
  15. }

Please note: fields marked with transient keyword aren’t stored in Redis.

To start use it you should use one of methods below:

RLiveObjectService.attach() - attaches object to Redis. Discard all the field values already in the detached instance
RLiveObjectService.merge() - overrides current object state in Redis with the given object state
RLiveObjectService.persist() - stores only new object

Code example:

  1. RLiveObjectService service = redisson.getLiveObjectService();
  2. MyLiveObject myObject = new MyLiveObject();
  3. myObject1.setId("1");
  4. // current state of myObject is now persisted and attached to Redis
  5. myObject = service.persist(myObject);
  6. MyLiveObject myObject = new MyLiveObject("1");
  7. // current state of myObject is now cleared and attached to Redis
  8. myObject = service.attach(myObject);
  9. MyLiveObject myObject = new MyLiveObject();
  10. myObject.setId("1");
  11. // current state of myObject is now merged to already existed object and attached to Redis
  12. myObject = service.merge(myObject);
  13. myObject.setValue("somevalue");
  14. // get Live Object by Id
  15. MyLiveObject myObject = service.get(MyLiveObject.class, "1");
  16. // find Live Objects by value field
  17. Collection<MyLiveObject> myObjects = service.find(MyLiveObject.class, Conditions.in("value", "somevalue", "somevalue2"));
  18. Collection<MyLiveObject> myObjects = service.find(MyLiveObject.class, Conditions.and(Conditions.in("value", "somevalue", "somevalue2"), Conditions.eq("secondfield", "test")));

“parent” field has a link to another instances of Live Object of the same type, but the type could be different. Redisson stores this link into Redis as a reference object and not the whole object state, so you continue to work with reference object as Live Object.

  1. //Redisson Live Object behavior:
  2. MyObject myObject = service.get(MyObject.class, "1");
  3. MyObject myParentObject = service.get(MyObject.class, "2");
  4. myObject.setValue(myParentObject);

Field types in the RLO can be almost anything, from Java util classes to collection/map types and of course your own custom objects, as long as it can be encoded and decoded by a supplied codec. More details about the codec can be found in the Advanced Usage section.

In order to keep RLOs behaving as closely to standard Java objects as possible, Redisson automatically converts the following standard Java field types to its counter types supported by Redisson RObject.

Standard Java Class Converted Redisson Class
SortedSet.class RedissonSortedSet.class
Set.class RedissonSet.class
ConcurrentMap.class RedissonMap.class
Map.class RedissonMap.class
BlockingDeque.class RedissonBlockingDeque.class
Deque.class RedissonDeque.class
BlockingQueue.class RedissonBlockingQueue.class
Queue.class RedissonQueue.class
List.class RedissonList.class

The conversion prefers the one nearer to the top of the table if a field type matches more than one entries. i.e. LinkedList implements Deque, List, Queue, it will be converted to a RedissonDeque because of this.

Instances of these Redisson classes retains their states/values/entries in Redis too, changes to them are directly reflected into Redis without keeping values in local VM.

9.2.3. Search by Object properties

Redisson provides comprehensive search engine for Live Object. To make a property participate in search it should be annotated with @RIndex annotation.

Usage example:

  1. @REntity
  2. public class MyObject {
  3. @RId
  4. private String id;
  5. @RIndex
  6. private String field1;
  7. @RIndex
  8. private Integer field2;
  9. @RIndex
  10. private Long field3;
  11. }

Different type of search conditions are available:

Conditions.and - AND condition for collection of nested conditions
Conditions.eq - EQUALS condition which restricts property to defined value
Conditions.or - OR condition for collection of nested conditions
Conditions.in - IN condition which restricts property to set of defined values
Conditions.gt - GREATER THAN condition which restricts property to defined value
Conditions.ge - GREATER THAN ON EQUAL condition which restricts property to defined value
Conditions.lt - LESS THAN condition which restricts property to defined value
Conditions.le - LESS THAN ON EQUAL condition which restricts property to defined value

Once object stored in Redis we can run search:

Search index
partitioning in cluster
Ultra-fast
search engine
Low JVM
memory consumption

Open-source version


Redisson PRO version

✔️ ✔️ ✔️
  1. RLiveObjectService liveObjectService = redisson.getLiveObjectService();
  2. liveObjectService.persist(new MyObject());
  3. // find all objects where field1 = value and field2 < 12 or field1 = value2 and field2 > 23 or field3 in [1, 2]
  4. Collection<MyObject> objects = liveObjectService.find(MyObject.class,
  5. Conditions.or(Conditions.and(Conditions.eq("field1", "value"), Conditions.lt("field2", 12)),
  6. Conditions.and(Conditions.eq("field1", "value2"), Conditions.gt("field2", 23)),
  7. Conditions.in("field3", 1L, 2L));

Search index expires after expireXXX() method call only if the Redis notify-keyspace-events setting contains the letters Kx.

9.2.4. Advanced Usage

As described before, RLO classes are proxy classes which can be fabricated when needed and then get cached in a RedissonClient instance against its original class. This process can be a bit slow and it is recommended to pre-register all the Redisson Live Object classes via RedissonLiveObjectService for any kind of delay-sensitive applications. The service can also be used to unregister a class if it is no longer needed. And of course it can be used to check if the class has already been registered.

  1. RLiveObjectService service = redisson.getLiveObjectService();
  2. service.registerClass(MyClass.class);
  3. service.unregisterClass(MyClass.class);
  4. Boolean registered = service.isClassRegistered(MyClass.class);

9.2.5. Annotations

@REntity

Applied to a class. The behaviour of each type of RLO can be customised through properties of the @REntity annotation. You can specify each of those properties to gain fine control over its behaviour.

  • namingScheme - You can specify a naming scheme which tells Redisson how to assign key names for each instance of this class. It is used to create a reference to an existing Redisson Live Object and materialising a new one in redis. It defaults to use Redisson provided DefaultNamingScheme.
  • codec - You can tell Redisson which Codec class you want to use for the RLO. Redisson will use an instance pool to locate the instance based on the class type. It defaults to JsonJacksonCodec provided by Redisson.
  • fieldTransformation - You can also specify a field transformation mode for the RLO. As mentioned before, in order to keep everything as close to standard Java as possible, Redisson will automatically transform fields with commonly-used Java util classes to Redisson compatible classes. This uses ANNOTATION_BASED as the default value. You can set it to IMPLEMENTATION_BASED which will skip the transformation.

@RId

Applied to a field. Defines primary key field of this class. The value of this field is used to create a reference to existing RLO. The field with this annotation is the only field that has its value also kept in the local VM. You can only have one RId annotation per class.

You can supply a generator strategy to the @RId annotation if you want the value of this field to be programatically generated. The default generator is null.

@RIndex

Applied to a field. Specifies that the field is used in search index. Allows to execute search query based on that field through RLiveObjectService.find method.

@RObjectField

Applied to a field. Allows to specify namingScheme and/or codec different from what is specified in @REntity.

@RCascade

Applied to a field. Specifies that the defined cascade types are applied to the object/objects contained in Live Object field. Different cascade types are available:

RCascadeType.ALL - Includes all cascade types
RCascadeType.PERSIST - Cascade persist operation during RLiveObjectService.persist() method invocation
RCascadeType.DETACH - Cascade detach operation during RLiveObjectService.detach() method invocation
RCascadeType.MERGE - Cascade merge operation during RLiveObjectService.merge() method invocation
RCascadeType.DELETE - Cascade delete operation during RLiveObjectService.delete() method invocation.

9.2.6. Restrictions

As mentioned above, the type of the RId field cannot be an Array type. This is due to the DefaultNamingScheme which cannot serialize and deserialize the Array type as of yet. This restriction can be lifted once the DefaultNamingScheme is improved. Since the RId field is encoded as part of the key name used by the underlying RMap, it makes no sense to create a RLO with just have one field. It is better to use a RBucket for this type of usage.

9.3. Distributed executor service

9.3.1. Distributed executor service. Overview

Redis based RExecutorService object implements of ExecutorService interface to run Callable, Runnable and Lambda tasks. Task and result objects are serialized using defined codec and stored in two request/response Redis queues. Redisson instance and task id can be injected in task object. Task id has size 128-bits and globally unique. This allows to process Redis data and execute distributed computations in fast and efficient way.

9.3.2. Distributed executor service. Workers

Worker runs task submitted through RExecutorService interface. Worker should be registered with WorkerOptions settings object. Each worker polls a task from a head of Redis queue in order it requested it. Polled tasks are executed with ExecutorService. Global default ExecutorService from Redisson configuration is used if ExecutorService in WorkerOptions isn’t defined.

Consider to use Redisson node if you need standalone jar which register and executes workers.

WorkerOptions exposes follow settings:

  1. WorkerOptions options = WorkerOptions.defaults()
  2. // Defines workers amount used to execute tasks.
  3. // Default is 1.
  4. .workers(2)
  5. // Defines Spring BeanFactory instance to execute tasks
  6. // with Spring's '@Autowired', '@Value' or JSR-330's '@Inject' annotation.
  7. .beanFactory(beanFactory)
  8. // Defines custom ExecutorService to execute tasks
  9. // Config.executor is used by default.
  10. .executorService()
  11. // Defines task timeout since task execution start moment
  12. .taskTimeout(60, TimeUnit.SECONDS)
  13. // add listener which is invoked on task successed event
  14. .addListener(new TaskSuccessListener() {
  15. public void onSucceeded(String taskId, T result) {
  16. // ...
  17. }
  18. })
  19. // add listener which is invoked on task failed event
  20. .addListener(new TaskFailureListener() {
  21. public void onFailed(String taskId, Throwable exception) {
  22. // ...
  23. }
  24. })
  25. // add listener which is invoked on task started event
  26. .addListener(new TaskStartedListener() {
  27. public void onStarted(String taskId) {
  28. // ...
  29. }
  30. })
  31. // add listener which is invoked on task finished event
  32. .addListener(new TaskFinishedListener() {
  33. public void onFinished(String taskId) {
  34. // ...
  35. }
  36. });

Code example of worker registration with options defined above:

  1. RExecutorService executor = redisson.getExecutorService("myExecutor");
  2. executor.registerWorkers(options);

9.3.3. Distributed executor service. Tasks

Redisson node doesn’t require presence of task classes in classpath. Task classes are loaded automatically by Redisson node ClassLoader. Thus each new task class doesn’t require restart of Redisson node.

Example with Callable task:

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

Example with Runnable task:

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

Follow options could be supplied during ExecutorService aquisition:

  1. ExecutorOptions options = ExecutorOptions.defaults()
  2. // Defines task retry interval at the end of which task is executed again.
  3. // ExecutorService worker re-schedule task execution retry every 5 seconds.
  4. //
  5. // Set 0 to disable.
  6. //
  7. // Default is 5 minutes
  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();

Example with Lambda task:

  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();

Each Redisson node has ready to use RedissonClient which could be injected using @RInject annotation.

9.3.4. Distributed executor service. Tasks with Spring beans

Redisson allows to inject not only RedissonClient and task id using @RInject annotation but also supports Spring’s @Autowire, @Value and JSR-330’s @Inject annotations. Injected Spring Bean service interface should implement Serializable.

Redisson uses Spring’s BeanFactory object for injection. It should be defined in Redisson Node configuration.

Example with Callable task:

  1. public class CallableTask implements Callable<Integer> {
  2. @Autowired
  3. private MySpringService service;
  4. @Value("myProperty")
  5. private String prop;
  6. @RInject
  7. private RedissonClient redissonClient;
  8. @Override
  9. public Integer call() throws Exception {
  10. RMap<String, Integer> map = redissonClient.getMap(prop);
  11. Integer result = service.someMethod();
  12. map.put("test", result);
  13. return result;
  14. }
  15. }
  1. RExecutorService executorService = redisson.getExecutorService("myExecutor", options);
  2. Future<Integer> future = executorService.submit(new CallableTask());
  3. Integer result = future.get();

9.3.5. Distributed executor service. Task execution cancellation

It’s easy to cancel any submitted task via RFuture.cancel() or RExecutorService.cancelTask() method. To handle case then task execution is already in progress you need to check Thread status for interruption with Thread.currentThread().isInterrupted() invocation:

  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. // map contains many entries
  9. for (Integer value : map.values()) {
  10. if (Thread.currentThread().isInterrupted()) {
  11. // task has been canceled
  12. return null;
  13. }
  14. result += value;
  15. }
  16. return result;
  17. }
  18. }
  19. RExecutorService executorService = redisson.getExecutorService("myExecutor");
  20. // submit tasks synchronously for asynchronous execution.
  21. RExecutorFuture<Long> future = executorService.submit(new CallableTask());
  22. // submit tasks asynchronously for asynchronous execution.
  23. RExecutorFuture<Long> future = executorService.submitAsync(new CallableTask());
  24. // cancel future
  25. future.cancel(true);
  26. // cancel by taskId
  27. executorService.cancelTask(future.getTaskId());

9.4. Distributed scheduled executor service

9.4.1. Distributed scheduled executor service. Overview

Redis based RScheduledExecutorService implements ScheduledExecutorService interface to schedule Callable, Runnable and Lambda tasks. Scheduled task is a job which needs to be execute in the future at a particular time one or more times. Task and result objects are serialized and stored in request/response Redis queues. Redisson instance and task id can be injected into task object. Task id has size 128-bits and globally unique. This allows to process Redis data and execute distributed computations in fast and efficient way.

9.4.2. Distributed scheduled executor service. Workers

Worker runs task submitted through RScheduledExecutorService interface. Worker should be registered with WorkerOptions settings object. Each worker polls a task from head of Redis queue in order it requested it. Polled tasks are executed with ExecutorService. Global default ExecutorService from Redisson configuration is used if ExecutorService in WorkerOptions isn’t defined.

Consider to use Redisson node if you need standalone jar which register and executes workers.

WorkerOptions exposes follow settings:

  1. WorkerOptions options = WorkerOptions.defaults()
  2. // Defines workers amount used to execute tasks.
  3. // Default is 1.
  4. .workers(2)
  5. // Defines Spring BeanFactory instance to execute tasks
  6. // with Spring's '@Autowired', '@Value' or JSR-330's '@Inject' annotation.
  7. .beanFactory(beanFactory)
  8. // Defines custom ExecutorService to execute tasks
  9. // Config.executor is used by default.
  10. .executorService()
  11. // Defines task timeout since task execution start moment
  12. .taskTimeout(60, TimeUnit.SECONDS)
  13. // add listener which is invoked on task successed event
  14. .addListener(new TaskSuccessListener() {
  15. public void onSucceeded(String taskId, T result) {
  16. // ...
  17. }
  18. })
  19. // add listener which is invoked on task failed event
  20. .addListener(new TaskFailureListener() {
  21. public void onFailed(String taskId, Throwable exception) {
  22. // ...
  23. }
  24. })
  25. // add listener which is invoked on task started event
  26. .addListener(new TaskStartedListener() {
  27. public void onStarted(String taskId) {
  28. // ...
  29. }
  30. })
  31. // add listener which is invoked on task finished event
  32. .addListener(new TaskFinishedListener() {
  33. public void onFinished(String taskId) {
  34. // ...
  35. }
  36. });

Code example of worker registration with options defined above:

  1. RScheduledExecutorService executor = redisson.getExecutorService("myExecutor");
  2. executor.registerWorkers(options);

9.4.3. Distributed scheduled executor service. Scheduling a task

Redisson node doesn’t require presence of task classes in classpath. Task classes are loaded automatically by Redisson node ClassLoader. Thus each new task class doesn’t require restart of Redisson node.

Example with Callable task:

  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. }

Follow options could be supplied during ExecutorService aquisition:

  1. ExecutorOptions options = ExecutorOptions.defaults()
  2. // Defines task retry interval at the end of which task is executed again.
  3. // ExecutorService worker re-schedule task execution retry every 5 seconds.
  4. //
  5. // Set 0 to disable.
  6. //
  7. // Default is 5 minutes
  8. options.taskRetryInterval(10, TimeUnit.MINUTES);
  1. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
  2. ScheduledFuture<Long> future = executorService.schedule(new CallableTask(), 10, TimeUnit.MINUTES);
  3. Long result = future.get();

Example with Lambda task:

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

Example with Runnable task:

  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. }
  16. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
  17. ScheduledFuture<?> future1 = executorService.schedule(new RunnableTask(123), 10, TimeUnit.HOURS);
  18. // ...
  19. ScheduledFuture<?> future2 = executorService.scheduleAtFixedRate(new RunnableTask(123), 10, 25, TimeUnit.HOURS);
  20. // ...
  21. ScheduledFuture<?> future3 = executorService.scheduleWithFixedDelay(new RunnableTask(123), 5, 10, TimeUnit.HOURS);

9.4.4. Distributed scheduled executor service. Scheduling a task with Spring beans

Redisson allows to inject not only RedissonClient using @RInject annotation but also supports Spring’s @Autowire, @Value and JSR-330’s @Inject annotations. Injected Spring Bean service interface should implement Serializable.

Redisson uses Spring’s BeanFactory object for injection. It should be defined in Redisson Node configuration.

Example with Callable task:

  1. public class RunnableTask implements Runnable {
  2. @Autowired
  3. private MySpringService service;
  4. @Value("myProperty")
  5. private String prop;
  6. @RInject
  7. private RedissonClient redissonClient;
  8. private long param;
  9. public RunnableTask() {
  10. }
  11. public RunnableTask(long param) {
  12. this.param = param;
  13. }
  14. @Override
  15. public void run() {
  16. RMap<String, Integer> map = redissonClient.getMap(prop);
  17. Integer result = service.someMethod();
  18. map.put("test", result);
  19. return result;
  20. }
  21. }
  1. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
  2. ScheduledFuture<?> future1 = executorService.schedule(new RunnableTask(123), 10, TimeUnit.HOURS);
  3. // ...
  4. ScheduledFuture<?> future2 = executorService.scheduleAtFixedRate(new RunnableTask(123), 10, 25, TimeUnit.HOURS);
  5. // ...
  6. ScheduledFuture<?> future3 = executorService.scheduleWithFixedDelay(new RunnableTask(123), 5, 10, TimeUnit.HOURS);

9.4.5. Distributed scheduled executor service. Scheduling a task with cron expression

Tasks scheduler service allows to define more complex schedule with cron expressions. Which fully compatible with Quartz cron format.

Example:

  1. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
  2. executorService.schedule(new RunnableTask(), CronSchedule.of("10 0/5 * * * ?"));
  3. // ...
  4. executorService.schedule(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));
  5. // ...
  6. executorService.schedule(new RunnableTask(), CronSchedule.weeklyOnDayAndHourAndMinute(12, 4, Calendar.MONDAY, Calendar.FRIDAY));

9.4.6. Distributed scheduled executor service. Task scheduling cancellation

Scheduled executor service provides two ways to cancel scheduled task via RScheduledFuture.cancel() or RScheduledExecutorService.cancelTask() method. To handle case then task execution is already in progress you need to check Thread status for interruption with Thread.currentThread().isInterrupted() invocation:

  1. public class RunnableTask 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. // map contains many entries
  9. for (Integer value : map.values()) {
  10. if (Thread.currentThread().isInterrupted()) {
  11. // task has been canceled
  12. return null;
  13. }
  14. result += value;
  15. }
  16. return result;
  17. }
  18. }
  19. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
  20. // submit tasks synchronously for asynchronous execution.
  21. RScheduledFuture<Long> future = executorService.schedule(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));
  22. // submit tasks asynchronously for asynchronous execution.
  23. RScheduledFuture<Long> future = executorService.scheduleAsync(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));
  24. // cancel future
  25. future.cancel(true);
  26. // cancel by taskId
  27. executorService.cancelTask(future.getTaskId());

9.5. Distributed MapReduce service

9.5.1 Distributed MapReduce service. Overview

Redisson provides MapReduce programming model to process large amount of data stored in Redis. Based on ideas from different implementations and Google’s MapReduce publication. Supported by different objects: RMap, RMapCache, RLocalCachedMap, RClusteredMap, RClusteredMapCache, RClusteredLocalCachedMap, RClusteredSet, RClusteredSetCache, RSet, RSetCache, RList, RSortedSet, RScoredSortedSet, RQueue, RBlockingQueue, RDeque, RBlockingDeque, RPriorityQueue and RPriorityDeque.

MapReduce model based on few objects: RMapper/RCollectionMapper, RReducer and RCollator.

All tasks for map and reduce phases are executed across Redisson Nodes.

For RLocalCachedMap, RClusteredMap, RClusteredMapCache, RClusteredLocalCachedMap, RClusteredSet, RClusteredSetCache objects Map phase is splitted to multiple sub-tasks and executes in parallel. For other objects Map phase is executed in single sub-task. Reduce phase is always splitted to multiple sub-tasks and executes in parallel. Sub-tasks amount equals to total amount of registered MapReduce workers.

1. RMapper applied only for Map objects and transforms each Map’s entry to intermediate key/value pair.

  1. public interface RMapper<KIn, VIn, KOut, VOut> extends Serializable {
  2. void map(KIn key, VIn value, RCollector<KOut, VOut> collector);
  3. }

2. RCollectionMapper applied only for Collection objects and transforms each Collection’s entry to intermediate key/value pair.

  1. public interface RCollectionMapper<VIn, KOut, VOut> extends Serializable {
  2. void map(VIn value, RCollector<KOut, VOut> collector);
  3. }

3. RReducer reduces a list of intermediate key/value pairs.

  1. public interface RReducer<K, V> extends Serializable {
  2. V reduce(K reducedKey, Iterator<V> values);
  3. }

4. RCollator converts reduced result to a single object.

  1. public interface RCollator<K, V, R> extends Serializable {
  2. R collate(Map<K, V> resultMap);
  3. }

Each type of task has ability to inject RedissonClient using @RInject annotation like this:

  1. public class WordMapper implements RMapper<String, String, String, Integer> {
  2. @RInject
  3. private RedissonClient redissonClient;
  4. @Override
  5. public void map(String key, String value, RCollector<String, Integer> collector) {
  6. // ...
  7. redissonClient.getAtomicLong("mapInvocations").incrementAndGet();
  8. }
  9. }

By default MapReduce time execution is not limited, but timeout could be defined if required:

  1. = list.<String, Integer>mapReduce()
  2. .mapper(new WordMapper())
  3. .reducer(new WordReducer())
  4. .timeout(60, TimeUnit.MINUTES);

9.5.2 Distributed MapReduce service. Map example

MapReduce is available for map type objects: RMap, RMapCache and RLocalCachedMap.

Below is word count example using MapReduce:

  1. Mapper object applied to each Map entry and split value by space to separate words.

    1. public class WordMapper implements RMapper<String, String, String, Integer> {
    2. @Override
    3. public void map(String key, String value, RCollector<String, Integer> collector) {
    4. String[] words = value.split("[^a-zA-Z]");
    5. for (String word : words) {
    6. collector.emit(word, 1);
    7. }
    8. }
    9. }
  2. Reducer object calculates the total sum for each word.

    1. public class WordReducer implements RReducer<String, Integer> {
    2. @Override
    3. public Integer reduce(String reducedKey, Iterator<Integer> iter) {
    4. int sum = 0;
    5. while (iter.hasNext()) {
    6. Integer i = (Integer) iter.next();
    7. sum += i;
    8. }
    9. return sum;
    10. }
    11. }
  3. Collator object counts total amount of words.

    1. public class WordCollator implements RCollator<String, Integer, Integer> {
    2. @Override
    3. public Integer collate(Map<String, Integer> resultMap) {
    4. int result = 0;
    5. for (Integer count : resultMap.values()) {
    6. result += count;
    7. }
    8. return result;
    9. }
    10. }
  4. Here is how to run all together:

    1. RMap<String, String> map = redisson.getMap("wordsMap");
    2. map.put("line1", "Alice was beginning to get very tired");
    3. map.put("line2", "of sitting by her sister on the bank and");
    4. map.put("line3", "of having nothing to do once or twice she");
    5. map.put("line4", "had peeped into the book her sister was reading");
    6. map.put("line5", "but it had no pictures or conversations in it");
    7. map.put("line6", "and what is the use of a book");
    8. map.put("line7", "thought Alice without pictures or conversation");
    9. RMapReduce<String, String, String, Integer> mapReduce
    10. = map.<String, Integer>mapReduce()
    11. .mapper(new WordMapper())
    12. .reducer(new WordReducer());
    13. // count occurrences of words
    14. Map<String, Integer> mapToNumber = mapReduce.execute();
    15. // count total words amount
    16. Integer totalWordsAmount = mapReduce.execute(new WordCollator());

9.5.3 Distributed MapReduce service. Collection example

MapReduce is available for collection type objects: RSet, RSetCache, RList, RSortedSet, RScoredSortedSet, RQueue, RBlockingQueue, RDeque, RBlockingDeque, RPriorityQueue and RPriorityDeque.

Below is word count example using MapReduce:

  1. public class WordMapper implements RCollectionMapper<String, String, Integer> {
  2. @Override
  3. public void map(String value, RCollector<String, Integer> collector) {
  4. String[] words = value.split("[^a-zA-Z]");
  5. for (String word : words) {
  6. collector.emit(word, 1);
  7. }
  8. }
  9. }
  1. public class WordReducer implements RReducer<String, Integer> {
  2. @Override
  3. public Integer reduce(String reducedKey, Iterator<Integer> iter) {
  4. int sum = 0;
  5. while (iter.hasNext()) {
  6. Integer i = (Integer) iter.next();
  7. sum += i;
  8. }
  9. return sum;
  10. }
  11. }
  1. public class WordCollator implements RCollator<String, Integer, Integer> {
  2. @Override
  3. public Integer collate(Map<String, Integer> resultMap) {
  4. int result = 0;
  5. for (Integer count : resultMap.values()) {
  6. result += count;
  7. }
  8. return result;
  9. }
  10. }
  1. RList<String> list = redisson.getList("myList");
  2. list.add("Alice was beginning to get very tired");
  3. list.add("of sitting by her sister on the bank and");
  4. list.add("of having nothing to do once or twice she");
  5. list.add("had peeped into the book her sister was reading");
  6. list.add("but it had no pictures or conversations in it");
  7. list.add("and what is the use of a book");
  8. list.add("thought Alice without pictures or conversation");
  9. RCollectionMapReduce<String, String, Integer> mapReduce
  10. = list.<String, Integer>mapReduce()
  11. .mapper(new WordMapper())
  12. .reducer(new WordReducer());
  13. // count occurrences of words
  14. Map<String, Integer> mapToNumber = mapReduce.execute();
  15. // count total words amount
  16. Integer totalWordsAmount = mapReduce.execute(new WordCollator());

9.6. RediSearch service

Redisson provides RediSearch integration. Supports field indexing of RMap and RJSONBucket objects, query execution and aggregation.

It has Async, Reactive and RxJava3 interfaces.

9.6.1. RediSearch service. Query execution

Code example for RMap object:

  1. RMap<String, SimpleObject> m = redisson.getMap("doc:1", new CompositeCodec(StringCodec.INSTANCE, redisson.getConfig().getCodec()));
  2. m.put("v1", new SimpleObject("name1"));
  3. m.put("v2", new SimpleObject("name2"));
  4. RMap<String, SimpleObject> m2 = redisson.getMap("doc:2", new CompositeCodec(StringCodec.INSTANCE, redisson.getConfig().getCodec()));
  5. m2.put("v1", new SimpleObject("name3"));
  6. m2.put("v2", new SimpleObject("name4"));
  7. RSearch s = redisson.getSearch();
  8. s.createIndex("idx", IndexOptions.defaults()
  9. .on(IndexType.HASH)
  10. .prefix(Arrays.asList("doc:")),
  11. FieldIndex.text("v1"),
  12. FieldIndex.text("v2"));
  13. SearchResult r = s.search("idx", "*", QueryOptions.defaults()
  14. .returnAttributes(new ReturnAttribute("v1"), new ReturnAttribute("v2")));
  15. SearchResult r = s.search("idx", "*", QueryOptions.defaults()
  16. .filters(QueryFilter.geo("field")
  17. .from(1, 1)
  18. .radius(10, GeoUnit.FEET)));

Code example for JSON object:

  1. public class TestClass {
  2. private List<Integer> arr;
  3. private String value;
  4. public TestClass() {
  5. }
  6. public TestClass(List<Integer> arr, String value) {
  7. this.arr = arr;
  8. this.value = value;
  9. }
  10. public List<Integer> getArr() {
  11. return arr;
  12. }
  13. public TestClass setArr(List<Integer> arr) {
  14. this.arr = arr;
  15. return this;
  16. }
  17. public String getValue() {
  18. return value;
  19. }
  20. public TestClass setValue(String value) {
  21. this.value = value;
  22. return this;
  23. }
  24. }
  25. RJsonBucket<TestClass> b = redisson.getJsonBucket("doc:1", new JacksonCodec<>(TestClass.class));
  26. b.set(new TestClass(Arrays.asList(1, 2, 3), "hello"));
  27. RSearch s = redisson.getSearch(StringCodec.INSTANCE);
  28. s.createIndex("idx", IndexOptions.defaults()
  29. .on(IndexType.JSON)
  30. .prefix(Arrays.asList("doc:")),
  31. FieldIndex.numeric("$..arr").as("arr"),
  32. FieldIndex.text("$..value").as("val"));
  33. SearchResult r = s.search("idx", "*", QueryOptions.defaults()
  34. .returnAttributes(new ReturnAttribute("arr"), new ReturnAttribute("val")));

9.6.2. RediSearch service. Aggregation

Code example for Map object:

  1. RMap<String, SimpleObject> m = redisson.getMap("doc:1", new CompositeCodec(StringCodec.INSTANCE, redisson.getConfig().getCodec()));
  2. m.put("v1", new SimpleObject("name1"));
  3. m.put("v2", new SimpleObject("name2"));
  4. RMap<String, SimpleObject> m2 = redisson.getMap("doc:2", new CompositeCodec(StringCodec.INSTANCE, redisson.getConfig().getCodec()));
  5. m2.put("v1", new SimpleObject("name3"));
  6. m2.put("v2", new SimpleObject("name4"));
  7. RSearch s = redisson.getSearch();
  8. s.createIndex("idx", IndexOptions.defaults()
  9. .on(IndexType.HASH)
  10. .prefix(Arrays.asList("doc:")),
  11. FieldIndex.text("v1"),
  12. FieldIndex.text("v2"));
  13. AggregationResult r = s.aggregate("idx", "*", AggregationOptions.defaults()
  14. .load("v1", "v2"));

Code example for JSON object:

  1. public class TestClass {
  2. private List<Integer> arr;
  3. private String value;
  4. public TestClass() {
  5. }
  6. public TestClass(List<Integer> arr, String value) {
  7. this.arr = arr;
  8. this.value = value;
  9. }
  10. public List<Integer> getArr() {
  11. return arr;
  12. }
  13. public TestClass setArr(List<Integer> arr) {
  14. this.arr = arr;
  15. return this;
  16. }
  17. public String getValue() {
  18. return value;
  19. }
  20. public TestClass setValue(String value) {
  21. this.value = value;
  22. return this;
  23. }
  24. }
  25. RJsonBucket<TestClass> b = redisson.getJsonBucket("doc:1", new JacksonCodec<>(TestClass.class));
  26. b.set(new TestClass(Arrays.asList(1, 2, 3), "hello"));
  27. RSearch s = redisson.getSearch(StringCodec.INSTANCE);
  28. s.createIndex("idx", IndexOptions.defaults()
  29. .on(IndexType.JSON)
  30. .prefix(Arrays.asList("doc:")),
  31. FieldIndex.numeric("$..arr").as("arr"),
  32. FieldIndex.text("$..value").as("val"));
  33. AggregationResult r = s.aggregate("idx", "*", AggregationOptions.defaults()
  34. .load("arr", "val"));

9.6.3. RediSearch service. Spellcheck

Code example.

  1. RSearch s = redisson.getSearch();
  2. s.createIndex("idx", IndexOptions.defaults()
  3. .on(IndexType.HASH)
  4. .prefix(Arrays.asList("doc:")),
  5. FieldIndex.text("t1"),
  6. FieldIndex.text("t2"));
  7. s.addDict("name", "hockey", "stik");
  8. Map<String, Map<String, Double>> res = s.spellcheck("idx", "Hocke sti", SpellcheckOptions.defaults()
  9. .includedTerms("name"));