6.1. Object holder

Java implementation of Redis based RBucket object is a holder for any type of object. Size is limited to 512Mb.

Code example:

  1. RBucket<AnyObject> bucket = redisson.getBucket("anyObject");
  2. bucket.set(new AnyObject(1));
  3. AnyObject obj = bucket.get();
  4. bucket.trySet(new AnyObject(3));
  5. bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
  6. bucket.getAndSet(new AnyObject(6));

Code example of Async interface usage:

  1. RBucket<AnyObject> bucket = redisson.getBucket("anyObject");
  2. RFuture<Void> future = bucket.setAsync(new AnyObject(1));
  3. RFuture<AnyObject> objfuture = bucket.getAsync();
  4. RFuture<Boolean> tsFuture = bucket.trySetAsync(new AnyObject(3));
  5. RFuture<Boolean> csFuture = bucket.compareAndSetAsync(new AnyObject(4), new AnyObject(5));
  6. RFuture<AnyObject> gsFuture = bucket.getAndSetAsync(new AnyObject(6));

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RBucketReactive<AnyObject> bucket = redisson.getBucket("anyObject");
  3. Mono<Void> mono = bucket.set(new AnyObject(1));
  4. Mono<AnyObject> objMono = bucket.get();
  5. Mono<Boolean> tsMono = bucket.trySet(new AnyObject(3));
  6. Mono<Boolean> csMono = bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
  7. Mono<AnyObject> gsMono = bucket.getAndSet(new AnyObject(6));

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RBucketRx<AnyObject> bucket = redisson.getBucket("anyObject");
  3. Completable rx = bucket.set(new AnyObject(1));
  4. Maybe<AnyObject> objRx = bucket.get();
  5. Single<Boolean> tsRx = bucket.trySet(new AnyObject(3));
  6. Single<Boolean> csRx = bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
  7. Maybe<AnyObject> gsRx = bucket.getAndSet(new AnyObject(6));



Use RBuckets interface to execute operations over multiple RBucket objects:

Code example:

  1. RBuckets buckets = redisson.getBuckets();
  2. // get all bucket values
  3. Map<String, V> loadedBuckets = buckets.get("myBucket1", "myBucket2", "myBucket3");
  4. Map<String, Object> map = new HashMap<>();
  5. map.put("myBucket1", new MyObject());
  6. map.put("myBucket2", new MyObject());
  7. // sets all or nothing if some bucket is already exists
  8. buckets.trySet(map);
  9. // store all at once
  10. buckets.set(map);

Code example of Async interface usage:

  1. RBuckets buckets = redisson.getBuckets();
  2. // get all bucket values
  3. RFuture<Map<String, V>> bucketsFuture = buckets.getAsync("myBucket1", "myBucket2", "myBucket3");
  4. Map<String, Object> map = new HashMap<>();
  5. map.put("myBucket1", new MyObject());
  6. map.put("myBucket2", new MyObject());
  7. // sets all or nothing if some bucket is already exists
  8. RFuture<Boolean> tsFuture = buckets.trySetAsync(map);
  9. // store all at once
  10. RFuture<Void> sFuture = buckets.setAsync(map);

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RBucketsReactive buckets = redisson.getBuckets();
  3. // get all bucket values
  4. Mono<Map<String, V>> bucketsMono = buckets.getAsync("myBucket1", "myBucket2", "myBucket3");
  5. Map<String, Object> map = new HashMap<>();
  6. map.put("myBucket1", new MyObject());
  7. map.put("myBucket2", new MyObject());
  8. // sets all or nothing if some bucket is already exists
  9. Mono<Boolean> tsMono = buckets.trySet(map);
  10. // store all at once
  11. Mono<Void> sMono = buckets.set(map);

Code example of RxJava interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RBucketsRx buckets = redisson.getBuckets();
  3. // get all bucket values
  4. Single<Map<String, V>> bucketsRx = buckets.get("myBucket1", "myBucket2", "myBucket3");
  5. Map<String, Object> map = new HashMap<>();
  6. map.put("myBucket1", new MyObject());
  7. map.put("myBucket2", new MyObject());
  8. // sets all or nothing if some bucket is already exists
  9. Single<Boolean> tsRx = buckets.trySet(map);
  10. // store all at once
  11. Completable sRx = buckets.set(map);

6.1.1. Object holder listeners

Redisson allows to bind listeners per RBucket object.

Listener class name Event description
org.redisson.api.listener.TrackingListener Data created/updated after read operation
org.redisson.api.listener.SetObjectListener Data created/updated
org.redisson.api.ExpiredObjectListener RBucket object expired
org.redisson.api.DeletedObjectListener RBucket object deleted

Usage example:

  1. RBucket<String> set = redisson.getBucket("anyObject");
  2. int listenerId = set.addListener(new SetObjectListener() {
  3. @Override
  4. public void onSet(String name) {
  5. // ...
  6. }
  7. });
  8. int listenerId = set.addListener(new DeletedObjectListener() {
  9. @Override
  10. public void onDeleted(String name) {
  11. // ...
  12. }
  13. });
  14. // ...
  15. set.removeListener(listenerId);

6.2. Binary stream holder

Java implementation of Redis based RBinaryStream object holds sequence of bytes. It extends RBucket interface and size is limited to 512Mb.

Code example:

  1. RBinaryStream stream = redisson.getBinaryStream("anyStream");
  2. byte[] content = ...
  3. stream.set(content);
  4. stream.getAndSet(content);
  5. stream.trySet(content);
  6. stream.compareAndSet(oldContent, content);

Code example of Async interface usage:

  1. RBinaryStream stream = redisson.getBinaryStream("anyStream");
  2. byte[] content = ...
  3. RFuture<Void> future = stream.set(content);
  4. RFuture<byte[]> future = stream.getAndSet(content);
  5. RFuture<Boolean> future = stream.trySet(content);
  6. RFuture<Boolean> future = stream.compareAndSet(oldContent, content);

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RBinaryStreamReactive stream = redisson.getBinaryStream("anyStream");
  3. ByteBuffer content = ...
  4. Mono<Void> mono = stream.set(content);
  5. Mono<byte[]> mono = stream.getAndSet(content);
  6. Mono<Boolean> mono = stream.trySet(content);
  7. Mono<Boolean> mono = stream.compareAndSet(oldContent, content);
  8. Mono<Integer> mono = stream.write(content);
  9. stream.position(0);
  10. Mono<Integer> mono = stream.read(b);

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RBinaryStreamRx stream = redisson.getBinaryStream("anyStream");
  3. ByteBuffer content = ...
  4. Completable rx = stream.set(content);
  5. Maybe<byte[]> rx = stream.getAndSet(content);
  6. Single<Boolean> rx = stream.trySet(content);
  7. Single<Boolean> rx = stream.compareAndSet(oldContent, content);
  8. Single<Integer> rx = stream.write(content);
  9. stream.position(0);
  10. Single<Integer> rx = stream.read(b);

Code example of java.io.InputStream and java.io.OutputStream interfaces usage:

  1. RBinaryStream stream = redisson.getBinaryStream("anyStream");
  2. InputStream is = stream.getInputStream();
  3. byte[] readBuffer = ...
  4. is.read(readBuffer);
  5. OutputStream os = stream.getOuputStream();
  6. byte[] contentToWrite = ...
  7. os.write(contentToWrite);

Code example of java.nio.channels.SeekableByteChannel interface usage:

  1. RBinaryStream stream = redisson.getBinaryStream("anyStream");
  2. SeekableByteChannel sbc = stream.getChannel();
  3. ByteBuffer readBuffer = ...
  4. sbc.read(readBuffer);
  5. sbc.position(0);
  6. ByteBuffer contentToWrite = ...
  7. sbc.write(contentToWrite);
  8. sbc.truncate(234);

Code example of java.nio.channels.AsynchronousByteChannel interface usage:

  1. RBinaryStream stream = redisson.getBinaryStream("anyStream");
  2. AsynchronousByteChannel sbc = stream.getAsynchronousChannel();
  3. ByteBuffer readBuffer = ...
  4. sbc.read(readBuffer);
  5. ByteBuffer contentToWrite = ...
  6. sbc.write(contentToWrite);

6.2.1. Binary stream holder listeners

Redisson allows to bind listeners per RBinaryStream object.

Listener class name Event description
org.redisson.api.listener.TrackingListener Data created/updated after read operation
org.redisson.api.listener.SetObjectListener Data created/updated
org.redisson.api.ExpiredObjectListener RBinaryStream object expired
org.redisson.api.DeletedObjectListener RBinaryStream object deleted

Usage example:

  1. RBinaryStream stream = redisson.getBinaryStream("anyObject");
  2. int listenerId = set.addListener(new DeletedObjectListener() {
  3. @Override
  4. public void onDeleted(String name) {
  5. // ...
  6. }
  7. });
  8. // ...
  9. set.removeListener(listenerId);

6.3. Geospatial holder

Java implementation of Redis based RGeo object is a holder for geospatial items.

Code example:

  1. RGeo<String> geo = redisson.getGeo("test");
  2. geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"),
  3. new GeoEntry(15.087269, 37.502669, "Catania"));
  4. Double distance = geo.dist("Palermo", "Catania", GeoUnit.METERS);
  5. Map<String, GeoPosition> positions = geo.pos("test2", "Palermo", "test3", "Catania", "test1");
  6. List<String> cities = geo.search(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));
  7. Map<String, GeoPosition> citiesWithPositions = geo.searchWithPosition(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));

Code example of Async interface usage:

  1. RGeo<String> geo = redisson.getGeo("test");
  2. RFuture<Long> addFuture = geo.addAsync(new GeoEntry(13.361389, 38.115556, "Palermo"),
  3. new GeoEntry(15.087269, 37.502669, "Catania"));
  4. RFuture<Double> distanceFuture = geo.distAsync("Palermo", "Catania", GeoUnit.METERS);
  5. RFuture<Map<String, GeoPosition>> positionsFuture = geo.posAsync("test2", "Palermo", "test3", "Catania", "test1");
  6. RFuture<List<String>> citiesFuture = geo.searchAsync(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));
  7. RFuture<Map<String, GeoPosition>> citiesWithPositions = geo.searchWithPositionAsync(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RGeoReactive<String> bucket = redisson.getGeo("test");
  3. Mono<Long> addFuture = geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"),
  4. new GeoEntry(15.087269, 37.502669, "Catania"));
  5. Mono<Double> distanceFuture = geo.dist("Palermo", "Catania", GeoUnit.METERS);
  6. Mono<Map<String, GeoPosition>> positionsFuture = geo.pos("test2", "Palermo", "test3", "Catania", "test1");
  7. Mono<List<String>> citiesFuture = geo.search(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));
  8. Mono<Map<String, GeoPosition>> citiesWithPositions = geo.searchWithPosition(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RGeoRx<String> bucket = redisson.getGeo("test");
  3. Single<Long> addFuture = geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"),
  4. new GeoEntry(15.087269, 37.502669, "Catania"));
  5. Single<Double> distanceFuture = geo.dist("Palermo", "Catania", GeoUnit.METERS);
  6. Single<Map<String, GeoPosition>> positionsFuture = geo.pos("test2", "Palermo", "test3", "Catania", "test1");
  7. Single<List<String>> citiesFuture = geo.search(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));
  8. Single<Map<String, GeoPosition>> citiesWithPositions = geo.searchWithPosition(GeoSearchArgs.from(15, 37).radius(200, GeoUnit.KILOMETERS));

6.4. BitSet

Java implementation of Redis based RBitSet object provides API similar to java.util.BitSet. It represents vector of bits that grows as needed. Size limited by Redis to 4 294 967 295 bits.

Code example:

  1. RBitSet set = redisson.getBitSet("simpleBitset");
  2. set.set(0, true);
  3. set.set(1812, false);
  4. set.clear(0);
  5. set.and("anotherBitset");
  6. set.xor("anotherBitset");

Code example of Async interface usage:

  1. RBitSetAsync set = redisson.getBitSet("simpleBitset");
  2. RFuture<Boolean> setFuture = set.setAsync(0, true);
  3. RFuture<Boolean> setFuture = set.setAsync(1812, false);
  4. RFuture<Void> clearFuture = set.clearAsync(0);
  5. RFuture<Void> andFuture = set.andAsync("anotherBitset);
  6. RFuture<Void> xorFuture = set.xorAsync("anotherBitset");

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RBitSetReactive stream = redisson.getBitSet("simpleBitset");
  3. Mono<Boolean> setMono = set.set(0, true);
  4. Mono<Boolean> setMono = set.set(1812, false);
  5. Mono<Void> clearMono = set.clear(0);
  6. Mono<Void> andMono = set.and("anotherBitset);
  7. Mono<Void> xorMono = set.xor("anotherBitset");

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RBitSetRx stream = redisson.getBitSet("simpleBitset");
  3. Single<Boolean> setRx = set.set(0, true);
  4. Single<Boolean> setRx = set.set(1812, false);
  5. Completable clearRx = set.clear(0);
  6. Completable andRx = set.and("anotherBitset);
  7. Completable xorRx = set.xor("anotherBitset");

6.4.1. BitSet data partitioning (distributed roaring bitmap)

Although ‘RBitSet’ object is cluster compatible its content isn’t scaled across multiple Redis master nodes. BitSet data partitioning available only in cluster mode and implemented by separate RClusteredBitSet object. It uses distributed implementation of roaring bitmap structure. Size is limited by whole Redis Cluster memory. More details about partitioning here).

Below is the list of all available BitSet implementations:

RedissonClient
method name
Data partitioning
support
Ultra-fast read/write
getBitSet()
open-source version
getBitSet()
Redisson PRO version
✔️
getClusteredBitSet()
available only in Redisson PRO
✔️ ✔️

Code example:

  1. RClusteredBitSet set = redisson.getClusteredBitSet("simpleBitset");
  2. set.set(0, true);
  3. set.set(1812, false);
  4. set.clear(0);
  5. set.addAsync("e");
  6. set.xor("anotherBitset");

6.5. AtomicLong

Java implementation of Redis based AtomicLong object provides API similar to java.util.concurrent.atomic.AtomicLong object.

Code example:

  1. RAtomicLong atomicLong = redisson.getAtomicLong("myAtomicLong");
  2. atomicLong.set(3);
  3. atomicLong.incrementAndGet();
  4. atomicLong.get();

Code example of Async interface usage:

  1. RAtomicLongAsync atomicLong = redisson.getAtomicLong("myAtomicLong");
  2. RFuture<Void> setFuture = atomicLong.setAsync(3);
  3. RFuture<Long> igFuture = atomicLong.incrementAndGetAsync();
  4. RFuture<Long> getFuture = atomicLong.getAsync();

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RAtomicLongReactive atomicLong = redisson.getAtomicLong("myAtomicLong");
  3. Mono<Void> setMono = atomicLong.set(3);
  4. Mono<Long> igMono = atomicLong.incrementAndGet();
  5. RFuture<Long> getMono = atomicLong.getAsync();

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RAtomicLongRx atomicLong = redisson.getAtomicLong("myAtomicLong");
  3. Completable setMono = atomicLong.set(3);
  4. Single<Long> igMono = atomicLong.incrementAndGet();
  5. Single<Long> getMono = atomicLong.getAsync();

6.6. AtomicDouble

Java implementation of Redis based AtomicDouble object.

Code example:

  1. RAtomicDouble atomicDouble = redisson.getAtomicDouble("myAtomicDouble");
  2. atomicDouble.set(2.81);
  3. atomicDouble.addAndGet(4.11);
  4. atomicDouble.get();

Code example of Async interface usage:

  1. RAtomicDoubleAsync atomicDouble = redisson.getAtomicDouble("myAtomicDouble");
  2. RFuture<Void> setFuture = atomicDouble.setAsync(2.81);
  3. RFuture<Double> agFuture = atomicDouble.addAndGetAsync(4.11);
  4. RFuture<Double> getFuture = atomicDouble.getAsync();

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RAtomicDoubleReactive atomicDouble = redisson.getAtomicDouble("myAtomicDouble");
  3. Mono<Void> setMono = atomicDouble.set(2.81);
  4. Mono<Double> agMono = atomicDouble.addAndGet(4.11);
  5. Mono<Double> getMono = atomicDouble.get();

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RAtomicDoubleRx atomicDouble = redisson.getAtomicDouble("myAtomicDouble");
  3. Completable setMono = atomicDouble.set(2.81);
  4. Single<Double> igMono = atomicDouble.addAndGet(4.11);
  5. Single<Double> getMono = atomicDouble.get();

6.7. Topic

Java implementation of Redis based RTopic object implements Publish / Subscribe mechanism. It allows to subscribe on events published with multiple instances of RTopic object with the same name.

Listeners are re-subscribed automatically after reconnection to Redis or Redis failover. All messages sent during absence of connection to Redis are lost. Use Reliable Topic for reliable delivery.

Code example:

  1. RTopic topic = redisson.getTopic("myTopic");
  2. int listenerId = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  3. @Override
  4. public void onMessage(String channel, SomeObject message) {
  5. //...
  6. }
  7. });
  8. // in other thread or JVM
  9. RTopic topic = redisson.getTopic("myTopic");
  10. long clientsReceivedMessage = topic.publish(new SomeObject());

Code example of Async interface usage:

  1. RTopicAsync topic = redisson.getTopic("myTopic");
  2. RFuture<Integer> listenerFuture = topic.addListenerAsync(SomeObject.class, new MessageListener<SomeObject>() {
  3. @Override
  4. public void onMessage(String channel, SomeObject message) {
  5. //...
  6. }
  7. });
  8. // in other thread or JVM
  9. RTopicAsync topic = redisson.getTopic("myTopic");
  10. RFuture<Long> publishFuture = topic.publishAsync(new SomeObject());

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RTopicReactive topic = redisson.getTopic("myTopic");
  3. Mono<Integer> listenerMono = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  4. @Override
  5. public void onMessage(String channel, SomeObject message) {
  6. //...
  7. }
  8. });
  9. // in other thread or JVM
  10. RTopicReactive topic = redisson.getTopic("myTopic");
  11. Mono<Long> publishMono = topic.publish(new SomeObject());

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RTopicRx topic = redisson.getTopic("myTopic");
  3. Single<Integer> listenerMono = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  4. @Override
  5. public void onMessage(String channel, SomeObject message) {
  6. //...
  7. }
  8. });
  9. // in other thread or JVM
  10. RTopicRx topic = redisson.getTopic("myTopic");
  11. Single<Long> publishMono = topic.publish(new SomeObject());

6.7.1. Topic pattern

Java implementation of Redis based RPatternTopic object. It allows to subscribe to multiple topics by specified glob-style pattern.

Listeners are re-subscribed automatically after reconnection to Redis or Redis failover.

Pattern examples:

  • topic? subscribes to topic1, topicA
  • topic?_my subscribes to topic_my, topic123_my, topicTEST_my
  • topic[ae] subscribes to topica and topice only

Code example:

  1. // subscribe to all topics by `topic*` pattern
  2. RPatternTopic patternTopic = redisson.getPatternTopic("topic*");
  3. int listenerId = patternTopic.addListener(Message.class, new PatternMessageListener<Message>() {
  4. @Override
  5. public void onMessage(String pattern, String channel, Message msg) {
  6. //...
  7. }
  8. });

Code example of Async interface usage:

  1. RPatternTopicAsync patternTopic = redisson.getPatternTopic("topic*");
  2. RFuture<Integer> listenerFuture = patternTopic.addListenerAsync(Message.class, new PatternMessageListener<Message>() {
  3. @Override
  4. public void onMessage(String pattern, String channel, Message msg) {
  5. //...
  6. }
  7. });

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RTopicReactive patternTopic = redisson.getPatternTopic("topic*");
  3. Mono<Integer> listenerMono = patternTopic.addListener(Message.class, new PatternMessageListener<Message>() {
  4. @Override
  5. public void onMessage(String pattern, String channel, Message msg) {
  6. //...
  7. }
  8. });

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RTopicRx patternTopic = redisson.getPatternTopic("topic*");
  3. Single<Integer> listenerSingle = patternTopic.addListener(Message.class, new PatternMessageListener<Message>() {
  4. @Override
  5. public void onMessage(String pattern, String channel, Message msg) {
  6. //...
  7. }
  8. });

6.7.2. Sharded topic

Java implementation of Redis based RShardedTopic object implements Sharded Publish / Subscribe mechanism. It allows to subscribe on events published with multiple instances of RShardedTopic object with the same name. Subscribe/publish operations are executed only on Redis node in Cluster which is bounded to specific topic name. Published messages via RShardedTopic aren’t broadcasted across all Redis nodes as for RTopic object. Which reduces network bandwidth and Redis load.

Listeners are re-subscribed automatically after reconnection to Redis or Redis failover. All messages sent during absence of connection to Redis are lost. Use Reliable Topic for reliable delivery.

Code example:

  1. RShardedTopic topic = redisson.getShardedTopic("myTopic");
  2. int listenerId = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  3. @Override
  4. public void onMessage(String channel, SomeObject message) {
  5. //...
  6. }
  7. });
  8. // in other thread or JVM
  9. RShardedTopic topic = redisson.getShardedTopic("myTopic");
  10. long clientsReceivedMessage = topic.publish(new SomeObject());

Code example of Async interface usage:

  1. RShardedTopicAsync topic = redisson.getShardedTopic("myTopic");
  2. RFuture<Integer> listenerFuture = topic.addListenerAsync(SomeObject.class, new MessageListener<SomeObject>() {
  3. @Override
  4. public void onMessage(String channel, SomeObject message) {
  5. //...
  6. }
  7. });
  8. // in other thread or JVM
  9. RShardedTopicAsync topic = redisson.getShardedTopic("myTopic");
  10. RFuture<Long> publishFuture = topic.publishAsync(new SomeObject());

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RShardedTopicReactive topic = redisson.getShardedTopic("myTopic");
  3. Mono<Integer> listenerMono = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  4. @Override
  5. public void onMessage(String channel, SomeObject message) {
  6. //...
  7. }
  8. });
  9. // in other thread or JVM
  10. RShardedTopicReactive topic = redisson.getShardedTopic("myTopic");
  11. Mono<Long> publishMono = topic.publish(new SomeObject());

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RShardedTopicRx topic = redisson.getShardedTopic("myTopic");
  3. Single<Integer> listenerMono = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  4. @Override
  5. public void onMessage(String channel, SomeObject message) {
  6. //...
  7. }
  8. });
  9. // in other thread or JVM
  10. RShardedTopicRx topic = redisson.getShardedTopic("myTopic");
  11. Single<Long> publishMono = topic.publish(new SomeObject());

6.8. Bloom filter

Redis based distributed RBloomFilter bloom filter for Java. Number of contained bits is limited to 2^32 with data partitioning to 2^63

Must be initialized with capacity size by tryInit(expectedInsertions, falseProbability) method before usage.

  1. RBloomFilter<SomeObject> bloomFilter = redisson.getBloomFilter("sample");
  2. // initialize bloom filter with
  3. // expectedInsertions = 55000000
  4. // falseProbability = 0.03
  5. bloomFilter.tryInit(55000000L, 0.03);
  6. bloomFilter.add(new SomeObject("field1Value", "field2Value"));
  7. bloomFilter.add(new SomeObject("field5Value", "field8Value"));
  8. bloomFilter.contains(new SomeObject("field1Value", "field8Value"));
  9. bloomFilter.count();

6.8.1. Bloom filter data partitioning

This feature available only in Redisson PRO edition.

Although ‘RBloomFilter’ object is cluster compatible its content isn’t scaled across multiple Redis master nodes. Bloom Filter data partitioning support available only in cluster mode and implemented by separate RClusteredBloomFilter object. This implementation uses more efficient distributed Redis memory allocation algorithm. It allows to “shrink” memory space consumed by unused bits across all Redis nodes. State of each instance is partitioned across all nodes in Redis cluster. Number of contained bits is limited to 2^63. More details about partitioning here).

Below is the list of all available BloomFilter implementations:

RedissonClient
method name
Data partitioning
support
Ultra-fast read/write Bits amount limit
getBloomFilter()
open-source version
2^32
getBloomFilter()
Redisson PRO version
✔️ 2^32
getClusteredBloomFilter()
available only in Redisson PRO
✔️ ✔️ 2^63
  1. RClusteredBloomFilter<SomeObject> bloomFilter = redisson.getClusteredBloomFilter("sample");
  2. // initialize bloom filter with
  3. // expectedInsertions = 255000000
  4. // falseProbability = 0.03
  5. bloomFilter.tryInit(255000000L, 0.03);
  6. bloomFilter.add(new SomeObject("field1Value", "field2Value"));
  7. bloomFilter.add(new SomeObject("field5Value", "field8Value"));
  8. bloomFilter.contains(new SomeObject("field1Value", "field8Value"));

6.9. HyperLogLog

Redis based distributed RHyperLogLog object for Java. Probabilistic data structure that lets you maintain counts of millions of items with extreme space efficiency.

It has Async, Reactive and RxJava3 interfaces.

  1. RHyperLogLog<Integer> log = redisson.getHyperLogLog("log");
  2. log.add(1);
  3. log.add(2);
  4. log.add(3);
  5. log.count();

6.10. LongAdder

Java implementation of Redis based LongAdder object provides API similar to java.util.concurrent.atomic.LongAdder object.

It maintains internal LongAdder object on client side and provides superior performance for both increment and decrement operations. Up to 12000x faster than similar AtomicLong object. Suitable for distributed metric objects.

Code example:

  1. RLongAdder atomicLong = redisson.getLongAdder("myLongAdder");
  2. atomicLong.add(12);
  3. atomicLong.increment();
  4. atomicLong.decrement();
  5. atomicLong.sum();

Object should be destroyed if it’s not used anymore, but it’s not necessary to call destroy method if Redisson goes shutdown.

  1. RLongAdder atomicLong = ...
  2. atomicLong.destroy();

6.11. DoubleAdder

Java implementation of Redis based DoubleAdder object provides API similar to java.util.concurrent.atomic.DoubleAdder object.

It maintains internal DoubleAdder object on client side and provides superior performance for both increment and decrement operations. Up to 12000x faster than similar AtomicDouble object. Suitable for distributed metric objects.

Code example:

  1. RLongDouble atomicDouble = redisson.getLongDouble("myLongDouble");
  2. atomicDouble.add(12);
  3. atomicDouble.increment();
  4. atomicDouble.decrement();
  5. atomicDouble.sum();

Object should be destroyed if it’s not used anymore, but it’s not necessary to call destroy method if Redisson goes shutdown.

  1. RLongDouble atomicDouble = ...
  2. atomicDouble.destroy();

6.12. RateLimiter

Redis based distributed RateLimiter object for Java restricts the total rate of calls either from all threads regardless of Redisson instance or from all threads working with the same Redisson instance. Doesn’t guarantee fairness.

Code example:

  1. RRateLimiter limiter = redisson.getRateLimiter("myLimiter");
  2. // Initialization required only once.
  3. // 5 permits per 2 seconds
  4. limiter.trySetRate(RateType.OVERALL, 5, 2, RateIntervalUnit.SECONDS);
  5. // acquire 3 permits or block until they became available
  6. limiter.acquire(3);

Code example of Async interface usage:

  1. RRateLimiter limiter = redisson.getRateLimiter("myLimiter");
  2. // Initialization required only once.
  3. // 5 permits per 2 seconds
  4. RFuture<Boolean> setRateFuture = limiter.trySetRate(RateType.OVERALL, 5, 2, RateIntervalUnit.SECONDS);
  5. // acquire 3 permits or block until they became available
  6. RFuture<Void> aquireFuture = limiter.acquire(3);

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RRateLimiterReactive limiter = redisson.getRateLimiter("myLimiter");
  3. // Initialization required only once.
  4. // 5 permits per 2 seconds
  5. Mono<Boolean> setRateMono = limiter.trySetRate(RateType.OVERALL, 5, 2, RateIntervalUnit.SECONDS);
  6. // acquire 3 permits or block until they became available
  7. Mono<Void> aquireMono = limiter.acquire(3);

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RRateLimiterRx limiter = redisson.getRateLimiter("anyObject");
  3. // Initialization required only once.
  4. // 5 permits per 2 seconds
  5. Single<Boolean> setRateRx = limiter.trySetRate(RateType.OVERALL, 5, 2, RateIntervalUnit.SECONDS);
  6. // acquire 3 permits or block until they became available
  7. Completable aquireRx = limiter.acquire(3);

6.13. Reliable Topic

Java implementation of Redis based RReliableTopic object implements Publish / Subscribe mechanism with reliable delivery of messages. In case of Redis connection interruption all missed messages are delivered after reconnection to Redis. Message considered as delivered when it was received by Redisson and submited for processing by topic listeners.

Each RReliableTopic object instance (subscriber) has own watchdog which is started when the first listener was registered. Subscriber expires after org.redisson.config.Config#reliableTopicWatchdogTimeout timeout if watchdog didn’t extend it to the next timeout time interval. This prevents against infinity grow of stored messages in topic due to Redisson client crash or any other reason when subscriber unable to consume messages.

Topic listeners are resubscribed automatically after reconnection to Redis or Redis failover.

Code example:

  1. RReliableTopic topic = redisson.getReliableTopic("anyTopic");
  2. topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  3. @Override
  4. public void onMessage(CharSequence channel, SomeObject message) {
  5. //...
  6. }
  7. });
  8. // in other thread or JVM
  9. RReliableTopic topic = redisson.getReliableTopic("anyTopic");
  10. long subscribersReceivedMessage = topic.publish(new SomeObject());

Code example of Async interface usage:

  1. RReliableTopicAsync topic = redisson.getReliableTopic("anyTopic");
  2. RFuture<String> listenerFuture = topic.addListenerAsync(SomeObject.class, new MessageListener<SomeObject>() {
  3. @Override
  4. public void onMessage(CharSequence channel, SomeObject message) {
  5. //...
  6. }
  7. });
  8. // in other thread or JVM
  9. RReliableTopicAsync topic = redisson.getReliableTopic("anyTopic");
  10. RFuture<Long> future = topic.publishAsync(new SomeObject());

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RReliableTopicReactive topic = redisson.getReliableTopic("anyTopic");
  3. Mono<String> listenerMono = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  4. @Override
  5. public void onMessage(CharSequence channel, SomeObject message) {
  6. //...
  7. }
  8. });
  9. // in other thread or JVM
  10. RReliableTopicReactive topic = redisson.getReliableTopic("anyTopic");
  11. Mono<Long> publishMono = topic.publish(new SomeObject());

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RReliableTopicRx topic = redisson.getReliableTopic("anyTopic");
  3. Single<String> listenerRx = topic.addListener(SomeObject.class, new MessageListener<SomeObject>() {
  4. @Override
  5. public void onMessage(CharSequence channel, SomeObject message) {
  6. //...
  7. }
  8. });
  9. // in other thread or JVM
  10. RReliableTopicRx topic = redisson.getReliableTopic("anyTopic");
  11. Single<Long> publisRx = topic.publish(new SomeObject());

6.14. Id generator

Redis based Java Id generator RIdGenerator generates unique numbers but not monotonically increased. At first request, batch of id numbers is allocated and cached on Java side till it’s exhausted. This approach allows to generate ids faster than RAtomicLong.

Default allocation size is 5000. Default start value is 0.

Code example:

  1. RIdGenerator generator = redisson.getIdGenerator("generator");
  2. // Initialize with start value = 12 and allocation size = 20000
  3. generator.tryInit(12, 20000);
  4. long id = generator.nextId();

Code example of Async interface usage:

  1. RIdGenerator generator = redisson.getIdGenerator("generator");
  2. // Initialize with start value = 12 and allocation size = 20000
  3. RFuture<Boolean> initFuture = generator.tryInitAsync(12, 20000);
  4. RFuture<Long> idFuture = generator.nextIdAsync();

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RIdGenerator generator = redisson.getIdGenerator("generator");
  3. // Initialize with start value = 12 and allocation size = 20000
  4. Mono<Boolean> initMono = generator.tryInit(12, 20000);
  5. Mono<Long> idMono = generator.nextId();

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RIdGenerator generator = redisson.getIdGenerator("generator");
  3. // Initialize with start value = 12 and allocation size = 20000
  4. Single<Boolean> initRx = generator.tryInit(12, 20000);
  5. Single<Long> idRx = generator.nextId();

6.15. JSON object holder

Java implementation of RJsonBucket object stores data in JSON format using JSON.* Redis commands. JSON data encoding/decoding handled by JsonCodec which is required parameter. Available implementation is org.redisson.codec.JacksonCodec.

6.15.1. JSON object holder local cache

Redisson provides JSON object holder implementation with local cache.

local cache - so called near cache used to speed up read operations and avoid network roundtrips. It caches whole JSON object on Redisson side and executes read operations up to 45x faster in comparison with common implementation. Local cache instances with the same name connected to the same pub/sub channel. This channel is used to exchange invalidate events between instances.

RedissonClient
method name
Local cache Ultra-fast
read/write
getJsonBucket()
open-source version
getJsonBucket()
Redisson PRO version
✔️
getLocalCachedJsonBucket()
Redisson PRO version
✔️ ✔️

Code example:

  1. RJsonBucket<AnyObject> bucket = redisson.getJsonBucket("anyObject", new JacksonCodec<>(AnyObject.class));
  2. bucket.set(new AnyObject(1));
  3. AnyObject obj = bucket.get();
  4. bucket.trySet(new AnyObject(3));
  5. bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
  6. bucket.getAndSet(new AnyObject(6));
  7. List<String> values = bucket.get(new JacksonCodec<>(new TypeReference<List<String>>() {}), "values");
  8. long aa = bucket.arrayAppend("$.obj.values", "t3", "t4");

Code example of Async interface usage:

  1. RJsonBucket<AnyObject> bucket = redisson.getJsonBucket("anyObject", new JacksonCodec<>(AnyObject.class));
  2. RFuture<Void> future = bucket.setAsync(new AnyObject(1));
  3. RFuture<AnyObject> objfuture = bucket.getAsync();
  4. RFuture<Boolean> tsFuture = bucket.trySetAsync(new AnyObject(3));
  5. RFuture<Boolean> csFuture = bucket.compareAndSetAsync(new AnyObject(4), new AnyObject(5));
  6. RFuture<AnyObject> gsFuture = bucket.getAndSetAsync(new AnyObject(6));
  7. RFutue<List<String>> gFuture = bucket.getAsync(new JacksonCodec<>(new TypeReference<List<String>>() {}), "obj.values");
  8. RFutue<Long> aaFuture = bucket.arrayAppendAsync("$.obj.values", "t3", "t4");

Code example of Reactive interface usage:

  1. RedissonReactiveClient redisson = redissonClient.reactive();
  2. RJsonBucketReactive<AnyObject> bucket = redisson.getJsonBucket("anyObject", new JacksonCodec<>(AnyObject.class));
  3. Mono<Void> mono = bucket.set(new AnyObject(1));
  4. Mono<AnyObject> objMono = bucket.get();
  5. Mono<Boolean> tsMono = bucket.trySet(new AnyObject(3));
  6. Mono<Boolean> csMono = bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
  7. Mono<AnyObject> gsMono = bucket.getAndSet(new AnyObject(6));
  8. Mono<List<String>> vsMono = bucket.get(new JacksonCodec<>(new TypeReference<List<String>>() {}), "values");
  9. Mono<Long> aaMono = bucket.arrayAppend("$.obj.values", "t3", "t4");

Code example of RxJava3 interface usage:

  1. RedissonRxClient redisson = redissonClient.rxJava();
  2. RJsonBucketRx<AnyObject> bucket = redisson.getJsonBucket("anyObject", new JacksonCodec<>(AnyObject.class));
  3. Completable rx = bucket.set(new AnyObject(1));
  4. Maybe<AnyObject> objRx = bucket.get();
  5. Single<Boolean> tsRx = bucket.trySet(new AnyObject(3));
  6. Single<Boolean> csRx = bucket.compareAndSet(new AnyObject(4), new AnyObject(5));
  7. Maybe<AnyObject> gsRx = bucket.getAndSet(new AnyObject(6));
  8. Single<List<String>> valuesRx = bucket.get(new JacksonCodec<>(new TypeReference<List<String>>() {}), "values");
  9. Single<Long> aaRx = bucket.arrayAppend("$.obj.values", "t3", "t4");