Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use distributed Collection in redisson

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use distributed collections in redisson. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Redisson distributed Collection 1. Mapping (Map)

The RMap Java object of Redisson's distributed Map structure implements the java.util.concurrent.ConcurrentMap interface and the java.util.Map interface. At the same time, the insertion order of elements is maintained. The maximum capacity of this object is limited by Redis, and the maximum number of elements is 4294,967,295.

RMap map = redisson.getMap ("anyMap"); SomeObject prevObject = map.put ("323", new SomeObject ()); SomeObject currentObject = map.putIfAbsent ("323", new SomeObject ()); SomeObject obj = map.remove ("123"); map.fastPut ("321", new SomeObject ()); map.fastRemove ("321"); Future putAsyncFuture = map.putAsync ("321"); Future fastPutAsyncFuture = map.fastPutAsync ("321"); map.fastPutAsync ("321", new SomeObject ()); map.fastRemoveAsync ("321") Mapping (Map) elimination mechanism (Eviction)

Redisson's distributed RMapCache Java object implements the elimination mechanism for a single element on the premise of RMap. At the same time, the insertion order of elements is still preserved. Because RMapCache is implemented based on RMap, it inherits both java.util.concurrent.ConcurrentMap interface and java.util.Map interface. The Spring Cache integration provided by Redisson is based on this object structure.

The current Redis itself does not support the elimination of elements in Hash, so all expired elements are cleaned up regularly through org.redisson.EvictionScheduler instances. In order to ensure the effective use of resources, a maximum of 100 expired elements are cleaned up per run. The start time of the task is automatically adjusted according to the actual number of cleanups last time, and the interval tends to be between 1 second and 2 hours. For example, if 100 elements are deleted during this cleanup, the next cleanup will be performed after 1 second (minimum interval). Once the amount of this cleanup is less than that of the last cleanup, the interval will be increased by 1.5 times.

RMapCache map = redisson.getMapCache ("anyMap"); / effective time ttl = 10 minutes map.put ("key1", new SomeObject (), 10, TimeUnit.MINUTES); / / valid time ttl = 10 minutes, maximum idle time maxIdleTime = 10 seconds map.put ("key1", new SomeObject (), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS); / / effective time = 3 seconds map.putIfAbsent ("key2", new SomeObject (), 3, TimeUnit.SECONDS) / / valid time ttl = 40 seconds, maximum idle time maxIdleTime = 10 seconds map.putIfAbsent ("key2", new SomeObject (), 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS); 1.2 Local cache mapping (LocalCachedMap)

In a particular scenario, when highly frequent read operations make network communication a bottleneck, using the distributed Map local cache RLocalCachedMapJava object provided by Redisson would be a good choice. According to the configuration parameters, RLocalCachedMap conditionally caches elements in a distributed Map to achieve efficient read operations. The following configuration parameters can be used to create this instance:

LocalCachedMapOptions options = LocalCachedMapOptions.defaults () / the elimination mechanism has several algorithm policies such as LFU, LRU and NONE. EvictionPolicy (EvictionPolicy.LFU) .cacheSize (1000) / / if the value is `True (true) `, an elimination message for this element will be sent to all other identical instances while the instance performs update and deletion operations. Other identical instances delete their own cache at the same time after receiving the message. The next time the element is read / / it will be fetched from the Redis server. .invalidateEntryOnChange (false) / / validity time of elements in each Map local cache. Default millisecond is .timeToLive (10000) / / or .timeToLive (10, TimeUnit.SECONDS) / / maximum idle time of elements in each Map local cache. Default millisecond is .maxIdle (10000) / / or .maxIdle (10, TimeUnit.SECONDS). RLocalCachedMap map = redisson.getLocalCachedMap ("test", options); map.put ("1", 1); map.put ("2", 2); map.fastPut ("3", 4); when the Map local cache object is no longer used, it should be destroyed manually, but not manually if the Redisson object is closed (shutdown). RLocalCachedMap map =. Map.destroy (); 1.3. Mapping (Map) data fragmentation

Map data fragmentation is a function in Redis cluster mode. The distributed RClusteredMap Java objects provided by Redisson are also implemented based on RMap. You can get more information here.

RClusteredMap map = redisson.getClusteredMap ("anyMap"); SomeObject prevObject = map.put ("123", new SomeObject ()); SomeObject currentObject = map.putIfAbsent ("323", new SomeObject ()); SomeObject obj = map.remove ("123"); map.fastPut ("321", new SomeObject ()); map.fastRemove ("321")

When using RClusteredMap in a specific scenario, highly frequent read operations make network communication as a bottleneck, using the distributed Map local cache RClusteredLocalCachedMapJava object in the cluster mode provided by Redisson will be a good choice. According to the configuration parameters, RClusteredLocalCachedMap conditionally caches the elements in a distributed Map in cluster mode, so as to achieve efficient read operations. The following configuration parameters can be used to create this instance:

LocalCachedMapOptions options = LocalCachedMapOptions.defaults () / / LFU, LRU and NONE policies are available .evictionPolicy (EvictionPolicy.LFU) .cacheSize (1000) / if the value is `True (true) `, an elimination message for this element will be sent to all other identical instances while the instance performs update and deletion operations. Other identical instances delete their own cache at the same time after receiving the message. The next time the element is read / / it will be fetched from the Redis server. .invalidateEntryOnChange (false) / / validity time of elements in each Map local cache. Default millisecond is .timeToLive (10000) / / or .timeToLive (10, TimeUnit.SECONDS) / / maximum idle time of elements in each Map local cache. Default millisecond is .maxIdle (10000) / / or .maxIdle (10, TimeUnit.SECONDS). RClusteredLocalCachedMap map = redisson.getClusteredLocalCachedMap ("test", options); map.put ("1", 1); map.put ("2", 2); map.fastPut ("3", 4)

You should destroy the Map locally cached objects manually when you are no longer using them. If the Redisson objects are closed (shutdown), you do not need to destroy them manually.

RClusteredLocalCachedMap map =... map.destroy ()

In addition to RClusteredLocalCachedMap, Redisson provides another cluster mode of distributed mapping (Map), which not only provides transparent data fragmentation, but also provides an elimination mechanism for each element. The RClusteredMapCache class provides the implementation of both RClusteredMap and RMapCache interfaces, respectively. Unlike RClusteredLocalCachedMap, the former's elimination mechanism is for elements held in Redis, while the latter's elimination mechanism is for elements in the local cache.

RClusteredMapCache map = redisson.getClusteredMapCache ("anyMap"); / effective time ttl = 10 minutes map.put ("key1", new SomeObject (), 10, TimeUnit.MINUTES); / / valid time ttl = 10 minutes, maximum idle time maxIdleTime = 10 seconds map.put ("key1", new SomeObject (), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS); / / effective time = 3 seconds map.putIfAbsent ("key2", new SomeObject (), 3, TimeUnit.SECONDS) / / effective time ttl = 40 seconds, maximum idle time maxIdleTime = 10 seconds map.putIfAbsent ("key2", new SomeObject (), 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS)

This feature is limited to the Redisson PRO version.

two。 Multi-valued mapping (Multimap)

Redisson's distributed RMultimap Java object allows a field value in Map to contain multiple elements. The total number of fields is limited by Redis, and a maximum of 4294,967,295 different fields are allowed per Multimap.

2.1. Multi-valued mapping based on Set (Multimap)

Set-based Multimap does not allow a field value to contain duplicate elements.

RSetMultimap map = redisson.getSetMultimap ("myMultimap"); map.put (new SimpleKey ("0"), new SimpleValue ("1"); map.put (new SimpleKey ("0"), new SimpleValue ("2")); map.put (new SimpleKey ("3"), new SimpleValue ("4")); Set allValues = map.get (new SimpleKey ("0")); List newValues = Arrays.asList (new SimpleValue ("7"), new SimpleValue ("6"), new SimpleValue ("5")) Set oldValues = map.replaceValues (new SimpleKey ("0"), newValues); Set removedValues = map.removeAll (new SimpleKey ("0")); 2.2. Multi-valued mapping based on list (List) (Multimap)

List-based Multimap allows duplicate elements under a field while maintaining the insertion order.

RListMultimap map = redisson.getListMultimap ("test1"); map.put (new SimpleKey ("0"), new SimpleValue ("1")); map.put (new SimpleKey ("0"), new SimpleValue ("2")); map.put (new SimpleKey ("0"), new SimpleValue ("1")); map.put (new SimpleKey ("3"), new SimpleValue ("4")); List allValues = map.get (new SimpleKey ("0")) Collection newValues = Arrays.asList (new SimpleValue ("7"), new SimpleValue ("6"), new SimpleValue ("5"); List oldValues = map.replaceValues (new SimpleKey ("0"), newValues); List removedValues = map.removeAll (new SimpleKey ("0")); 2.3. Multi-valued mapping (Multimap) elimination mechanism (Eviction)

The obsolescence mechanism of Multimap objects is implemented through different interfaces. They are the RSetMultimapCache interface and the RListMultimapCache interface, corresponding to the Multimaps of Set and List, respectively.

All expired elements are cleaned up periodically through org.redisson.EvictionScheduler instances. In order to ensure the effective use of resources, a maximum of 100 expired elements are cleaned up per run. The start time of the task is automatically adjusted according to the actual number of cleanups last time, and the interval tends to be between 1 second and 2 hours. For example, if 100 elements are deleted during this cleanup, the next cleanup will be performed after 1 second (minimum interval). Once the amount of this cleanup is less than that of the last cleanup, the interval will be increased by 1.5 times.

Examples of using RSetMultimapCache:

RSetMultimapCache multimap = redisson.getSetMultimapCache ("myMultimap"); multimap.put ("1", "a"); multimap.put ("1", "b"); multimap.put ("1", "c"); multimap.put ("2", "e"); multimap.put ("2", "f"); multimap.expireKey ("2", 10, TimeUnit.MINUTES); 3. Set (Set)

The RSet Java object of Redisson's distributed Set structure implements the java.util.Set interface. The uniqueness of each element is ensured by comparing the states of each element. The maximum capacity of this object is limited by Redis, and the maximum number of elements is 4294,967,295.

RSet set = redisson.getSet ("anySet"); set.add (new SomeObject ()); set.remove (new SomeObject ())

Set objects in the Redisson PRO version can also support single collection data fragmentation in a Redis cluster environment.

3.1. Set phase-out mechanism (Eviction)

Redisson's distributed RSetCache Java object implements the elimination mechanism for a single element on the premise of RSet. Because RSetCache is implemented based on RSet, it also integrates the java.util.Set interface.

The current Redis itself does not support the elimination of elements in Set, so all expired elements are cleaned up regularly through org.redisson.EvictionScheduler instances. In order to ensure the effective use of resources, a maximum of 100 expired elements are cleaned up per run. The start time of the task is automatically adjusted according to the actual number of cleanups last time, and the interval tends to be between 1 second and 2 hours. For example, if 100 elements are deleted during this cleanup, the next cleanup will be performed after 1 second (minimum interval). Once the amount of this cleanup is less than that of the last cleanup, the interval will be increased by 1.5 times.

RSetCache set = redisson.getSetCache ("anySet"); / / ttl = 10 secondsset.add (new SomeObject (), 10, TimeUnit.SECONDS); 3.2. Set (Set) data fragmentation

Set data fragmentation is a function in Redis cluster mode. The distributed RClusteredSet Java objects provided by Redisson are also implemented based on RSet. You can get more information here.

RClusteredSet set = redisson.getClusteredSet ("anySet"); set.add (new SomeObject ()); set.remove (new SomeObject ())

In addition to RClusteredSet, Redisson also provides another cluster mode of distributed set (Set), which not only provides transparent data fragmentation, but also provides an elimination mechanism for each element. The RClusteredSetCache class provides the implementation of both RClusteredSet and RSetCache interfaces, respectively. Of course, these are all based on the implementation of java.util.Set interfaces.

This feature is limited to the Redisson PRO version.

4. Ordered set (SortedSet)

Redisson's distributed RSortedSet Java object implements the java.util.SortedSet interface. On the premise of ensuring the uniqueness of elements, the sorting of elements is realized through the Comparator interface.

RSortedSet set = redisson.getSortedSet ("anySet"); set.trySetComparator (new MyComparator ()); / / configuration element comparator set.add (3); set.add (1); set.add (2); set.removeAsync (0); set.addAsync (5); 5. Scoring sort set (ScoredSortedSet)

Redisson's distributed RScoredSortedSet Java object is a collection that can be sorted by the element score specified at the time of insertion. It also ensures the uniqueness of the element.

RScoredSortedSet set = redisson.getScoredSortedSet ("simple"); set.add (0.13, new SomeObject (a, b)); set.addAsync (0.251, new SomeObject (c, d)); set.add (0.302, new SomeObject (g, d)); set.pollFirst (); set.pollLast (); int index = set.rank (new SomeObject (g, d)); / / get the position of the element in the collection Double score = set.getScore (g, d) / / get the score of the element 6. Dictionary sort set (LexSortedSet)

Redisson's distributed RLexSortedSet Java object implements the java.util.Set interface while arranging all string elements in lexicographic order. Its formula also ensures the uniqueness of string elements.

RLexSortedSet set = redisson.getLexSortedSet ("simple"); set.add ("d"); set.addAsync ("e"); set.add ("f"); set.lexRangeTail ("d", false); set.lexCountHead ("e"); set.lexRange ("d", true, "z", false); 7. List (List)

The RList Java object of the Redisson distributed list (List) structure implements the java.util.List interface while ensuring the order in which elements are inserted. The maximum capacity of this object is limited by Redis, and the maximum number of elements is 4294,967,295.

RList list = redisson.getList ("anyList"); list.add (new SomeObject ()); list.get (0); list.remove (new SomeObject ()); 8. Line up (Queue)

The RQueue Java object of Redisson distributed unbounded queue (Queue) structure implements the java.util.Queue interface. Although there is no initial size (boundary) limit for RQueue objects, the maximum capacity of objects is limited by Redis, with a maximum number of elements of 4294,967,295.

RQueue queue = redisson.getQueue ("anyQueue"); queue.add (new SomeObject ()); SomeObject obj = queue.peek (); SomeObject someObj = queue.poll (); 9. Double-ended queue (Deque)

The RDeque Java object of Redisson distributed unbounded double-ended queue (Deque) structure implements the java.util.Deque interface. Although there is no initial size (boundary) limit for RDeque objects, the maximum capacity of objects is limited by Redis, with a maximum number of elements of 4294,967,295.

RDeque queue = redisson.getDeque ("anyDeque"); queue.addFirst (new SomeObject ()); queue.addLast (new SomeObject ()); SomeObject obj = queue.removeFirst (); SomeObject someObj = queue.removeLast (); 10. Blocking queue (Blocking Queue)

The RBlockingQueue Java object of Redisson distributed unbounded blocking queue (BlockingQueue) structure implements the java.util.concurrent.BlockingQueue interface. Although there is no initial size (boundary) limit for RBlockingQueue objects, the maximum capacity of objects is limited by Redis, with a maximum number of elements of 4294,967,295.

RBlockingQueue queue = redisson.getBlockingQueue ("anyQueue"); queue.offer (new SomeObject ()); SomeObject obj = queue.peek (); SomeObject someObj = queue.poll (); SomeObject ob = queue.poll (10, TimeUnit.MINUTES)

Poll, pollFromAny, pollLastAndOfferFirstTo and take methods use topic subscription publishing implementation internally. After Redis node failover (master-slave switching) or disconnection reconnection, the built-in related topic listener will automatically complete the topic re-subscription.

11. Bounded congestion queue (Bounded Blocking Queue)

The RBoundedBlockingQueue Java object of Redisson distributed bounded blocking queue (BoundedBlockingQueue) structure implements the java.util.concurrent.BlockingQueue interface. The maximum capacity of this object is limited by Redis, and the maximum number of elements is 4294,967,295. The initial capacity (boundary) of the queue must be set before use.

RBoundedBlockingQueue queue = redisson.getBoundedBlockingQueue ("anyQueue"); / / return `true (true) `if the initial capacity (boundary) is set successfully, / / return `false (false)` if the initial capacity (boundary) is close to exist. Queue.trySetCapacity (2); queue.offer (new SomeObject (1)); queue.offer (new SomeObject (2)); / / the capacity is full at this time, and the following code will be blocked until it is free. Queue.put (new SomeObject ()); SomeObject obj = queue.peek (); SomeObject someObj = queue.poll (); SomeObject ob = queue.poll (10, TimeUnit.MINUTES)

Poll, pollFromAny, pollLastAndOfferFirstTo and take methods use topic subscription publishing implementation internally. After Redis node failover (master-slave switching) or disconnection reconnection, the built-in related topic listener will automatically complete the topic re-subscription.

twelve。 Blocking double end queue (Blocking Deque)

The RBlockingDeque Java object of Redisson distributed unbounded blocking double-ended queue (BlockingDeque) structure implements the java.util.concurrent.BlockingDeque interface. Although there is no initial size (boundary) limit for RBlockingDeque objects, the maximum capacity of objects is limited by Redis, with a maximum number of elements of 4294,967,295.

RBlockingDeque deque = redisson.getBlockingDeque ("anyDeque"); deque.putFirst (1); deque.putLast (2); Integer firstValue = queue.takeFirst (); Integer lastValue = queue.takeLast (); Integer firstValue = queue.pollFirst (10, TimeUnit.MINUTES); Integer lastValue = queue.pollLast (3, TimeUnit.MINUTES)

Poll, pollFromAny, pollLastAndOfferFirstTo and take methods use topic subscription publishing implementation internally. After Redis node failover (master-slave switching) or disconnection reconnection, the built-in related topic listener will automatically complete the topic re-subscription.

13. Blocking Fair queue (Blocking Fair Queue)

The RBlockingFairQueue Java object of Redisson distributed unbounded blocking fair queuing (BlockingFairQueue) architecture implements the RBlockingQueue interface of Redisson distributed unbounded blocking queue (BlockingQueue) architecture, and solves the problem that the number of messages received by "distant" clients is lower than that of "near" clients due to the influence of network delay in complex network environment. As a result, the overload of individual processing nodes caused by this phenomenon is solved.

Based on the distributed unbounded blocking queue, the mechanism of fair access to messages is adopted, which not only ensures the first-in order of the messages obtained by poll and take methods, but also enables the messages in the queue to be evenly distributed all over the processing nodes in the complex distributed environment.

RBlockingFairQueue queue = redisson.getBlockingFairQueue ("myQueue"); queue.offer (new SomeObject ()); SomeObject obj = queue.peek (); SomeObject someObj = queue.poll (); SomeObject ob = queue.poll (10, TimeUnit.MINUTES); 14. Delayed queuing (Delayed Queue)

The RDelayedQueue Java object of Redisson distributed delay queue (DelayedQueue) structure provides the function of delaying adding items to the queue on the basis of implementing the RQueue interface. This function can be used to implement the transmission strategy in which the message delivery delay increases or decays geometrically.

RQueue distinationQueue =... RDelayedQueue delayedQueue = getDelayedQueue (distinationQueue); / / send the message to the specified queue delayedQueue.offer ("msg1", 10, TimeUnit.SECONDS) after 10 seconds; / / send the message to the specified queue delayedQueue.offer ("msg2", 1, TimeUnit.MINUTES) after a minute; if the object is no longer needed, it should be destroyed actively. You don't have to destroy it actively only if the related Redisson object also needs to be closed. RDelayedQueue delayedQueue =... delayedQueue.destroy (); 15. Priority queue (Priority Queue)

The distributed priority queue (Priority Queue) Java object based on Redis implements the interface of java.util.Queue. Elements can be sorted through the Comparator interface.

RPriorityQueue queue = redisson.getPriorityQueue ("anyQueue"); queue.trySetComparator (new MyComparator ()); / / specified object comparator queue.add (3); queue.add (1); queue.add (2); queue.removeAsync (0); queue.addAsync (5); queue.poll (); 16. Priority double-ended queue (Priority Deque)

The distributed priority double-end queue (Priority Deque) Java object based on Redis implements the interface of java.util.Deque. Elements can be sorted through the Comparator interface.

RPriorityDeque queue = redisson.getPriorityDeque ("anyQueue"); queue.trySetComparator (new MyComparator ()); / / specify object comparator queue.addLast (3); queue.addFirst (1); queue.add (2); queue.removeAsync (0); queue.addAsync (5); queue.pollFirst (); queue.pollLast (); on how to use distributed collections in redisson, so much for sharing here. I hope the above can be helpful and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report