redission
1,pom.xml
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>version</version> </dependency>
2,redissionUtils
public class RedissionUtils { private static Logger logger = LoggerFactory.getLogger(RedissionUtils.class); private static RedissionUtils redisUtils; private RedissionUtils() { } /** * Provide singleton mode * * @return */ public static RedissionUtils getInstance() { if (redisUtils == null) synchronized (RedisUtils.class) { if (redisUtils == null) redisUtils = new RedissionUtils(); } return redisUtils; } /** * Redisson is created using config. Redisson is the basic class used to connect to Redis Server * * @param config * @return */ public RedissonClient getRedisson(Config config) { RedissonClient redisson = Redisson.create(config); logger.info("Successfully connected Redis Server"); return redisson; } /** * Create Redisson using ip address and port * * @param ip * @param port * @return */ public RedissonClient getRedisson(String ip, String port) { Config config = new Config(); config.useSingleServer().setAddress(ip + ":" + port); RedissonClient redisson = Redisson.create(config); logger.info("Successfully connected Redis Server" + "\t" + "connect" + ip + ":" + port + "The server"); return redisson; } /** * Close Redisson client connection * * @param redisson */ public void closeRedisson(RedissonClient redisson) { redisson.shutdown(); logger.info("Successfully closed Redis Client connect"); } /** * Get string object * * @param redisson * @param objectName * @return */ public <T> RBucket<T> getRBucket(RedissonClient redisson, String objectName) { RBucket<T> bucket = redisson.getBucket(objectName); return bucket; } /** * Get Map object * * @param redisson * @param objectName * @return */ public <K, V> RMap<K, V> getRMap(RedissonClient redisson, String objectName) { RMap<K, V> map = redisson.getMap(objectName); return map; } /** * Get ordered collection * * @param redisson * @param objectName * @return */ public <V> RSortedSet<V> getRSortedSet(RedissonClient redisson, String objectName) { RSortedSet<V> sortedSet = redisson.getSortedSet(objectName); return sortedSet; } /** * Get collection * * @param redisson * @param objectName * @return */ public <V> RSet<V> getRSet(RedissonClient redisson, String objectName) { RSet<V> rSet = redisson.getSet(objectName); return rSet; } /** * Get list * * @param redisson * @param objectName * @return */ public <V> RList<V> getRList(RedissonClient redisson, String objectName) { RList<V> rList = redisson.getList(objectName); return rList; } /** * Get queue * * @param redisson * @param objectName * @return */ public <V> RQueue<V> getRQueue(RedissonClient redisson, String objectName) { RQueue<V> rQueue = redisson.getQueue(objectName); return rQueue; } /** * Get double ended queue * * @param redisson * @param objectName * @return */ public <V> RDeque<V> getRDeque(RedissonClient redisson, String objectName) { RDeque<V> rDeque = redisson.getDeque(objectName); return rDeque; } /** * This method is not available in Redisson 1.2. It is available in version 1.2.2 * * @param redisson * @param objectName * @return */ /** * public <V> RBlockingQueue<V> getRBlockingQueue(RedissonClient * redisson,String objectName){ RBlockingQueue * rb=redisson.getBlockingQueue(objectName); return rb; } */ /** * Acquire lock * * @param redisson * @param objectName * @return */ public RLock getRLock(RedissonClient redisson, String objectName) { RLock rLock = redisson.getLock(objectName); return rLock; } /** * Get atomic number * * @param redisson * @param objectName * @return */ public RAtomicLong getRAtomicLong(RedissonClient redisson, String objectName) { RAtomicLong rAtomicLong = redisson.getAtomicLong(objectName); return rAtomicLong; } /** * Get count lock * * @param redisson * @param objectName * @return */ public RCountDownLatch getRCountDownLatch(RedissonClient redisson, String objectName) { RCountDownLatch rCountDownLatch = redisson .getCountDownLatch(objectName); return rCountDownLatch; } /** * Get the Topic of the message * * @param redisson * @param objectName * @return */ public <M> RTopic<M> getRTopic(RedissonClient redisson, String objectName) { RTopic<M> rTopic = redisson.getTopic(objectName); return rTopic; } }
Note: reission supports multiple connection modes:
//stand-alone RedissonClient redisson = Redisson.create(); Config config = new Config(); config.useSingleServer().setAddress("myredisserver:6379"); RedissonClient redisson = Redisson.create(config); //Master-slave Config config = new Config(); config.useMasterSlaveServers() .setMasterAddress("127.0.0.1:6379") .addSlaveAddress("127.0.0.1:6389", "127.0.0.1:6332", "127.0.0.1:6419") .addSlaveAddress("127.0.0.1:6399"); RedissonClient redisson = Redisson.create(config); //sentry Config config = new Config(); config.useSentinelServers() .setMasterName("mymaster") .addSentinelAddress("127.0.0.1:26389", "127.0.0.1:26379") .addSentinelAddress("127.0.0.1:26319"); RedissonClient redisson = Redisson.create(config); //colony Config config = new Config(); config.useClusterServers() .setScanInterval(2000) // cluster state scan interval in milliseconds .addNodeAddress("127.0.0.1:7000", "127.0.0.1:7001") .addNodeAddress("127.0.0.1:7002"); RedissonClient redisson = Redisson.create(config);
3. Various distributed "locks" based on redistribution:
1) Reentrant lock:
Redisson's distributed reentrant lock RLock implements Java util. concurrent. locks. Lock interface, and support automatic expiration and unlocking. It also provides asynchronous, Reactive and RxJava2 standard interfaces.
// Most common usage RLock lock = redisson.getLock("anyLock"); lock.lock(); //... lock.unlock(); //In addition, Redisson also provides the parameter of leaseTime to specify the locking time through the locking method. After this time, the lock will be unlocked automatically. // Automatically unlock 10 seconds after locking // There is no need to call the unlock method to unlock manually lock.lock(10, TimeUnit.SECONDS); // Try to lock, wait for 100 seconds at most, and unlock automatically 10 seconds after locking boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); if (res) { try { ... } finally { lock.unlock(); } }
As we all know, if the Redisson node responsible for storing the distributed lock goes down and the lock is in the locked state, the lock will be locked. In order to avoid this situation, Redisson provides a watchdog to monitor the lock. Its function is to continuously extend the validity of the lock before the Redisson instance is closed. By default, the timeout time for the watchdog to check the lock is 30 seconds. You can also modify config Lockwatchdogtimeout to specify otherwise.
Redisson also provides asynchronous execution methods for distributed locks:
RLock lock = redisson.getLock("anyLock"); lock.lockAsync(); lock.lockAsync(10, TimeUnit.SECONDS); Future<Boolean> res = lock.tryLockAsync(100, 10, TimeUnit.SECONDS);
RLock objects fully comply with the Java Lock specification. In other words, only processes with locks can be unlocked, and other processes will throw an IllegalMonitorStateException error.
2) Fair Lock:
It ensures that when multiple Redisson client threads request locking at the same time, they are preferentially allocated to the thread that makes the request first. All request threads will queue in a queue. When a thread goes down, Redisson will wait for 5 seconds before continuing to the next thread, that is, if the first five threads are waiting, the next thread will wait for at least 25 seconds. The use method is the same as above. The following methods are used when obtaining:
RLock fairLock = redisson.getFairLock("anyLock");
3) Interlock (MultiLock):
Redisson distributed interlocking RedissonMultiLock objects based on Redis can associate multiple RLock objects into an interlocking, and each RLock object instance can come from different redisson instances.
RLock lock1 = redissonInstance1.getLock("lock1"); RLock lock2 = redissonInstance2.getLock("lock2"); RLock lock3 = redissonInstance3.getLock("lock3"); RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3); // Simultaneous locking: lock1 lock2 lock3 // All locks are locked successfully. lock.lock(); ... lock.unlock(); //In addition, Redisson also provides the parameter of leaseTime to specify the locking time through the locking method. After this time, the lock will be unlocked automatically. RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3); // Lock lock1, lock2 and lock3. If they are not unlocked manually, they will be unlocked automatically after 10 seconds lock.lock(10, TimeUnit.SECONDS); // Wait for 100 seconds for locking and unlock automatically after 10 seconds of successful locking boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); ... lock.unlock();
4) Red lock:
Redisson red lock redisson red lock object based on Redis implements the locking algorithm introduced by redislock. This object can also be used to associate multiple RLock objects into a red lock. Each RLock object instance can come from different redisson instances.
RLock lock1 = redissonInstance1.getLock("lock1"); RLock lock2 = redissonInstance2.getLock("lock2"); RLock lock3 = redissonInstance3.getLock("lock3"); RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3); // Simultaneous locking: lock1 lock2 lock3 // Red locks are successful when they are successfully locked on most nodes. lock.lock(); ... lock.unlock(); //In addition, Redisson also provides the parameter of leaseTime to specify the locking time through the locking method. After this time, the lock will be unlocked automatically. RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3); // Lock lock1, lock2 and lock3. If they are not unlocked manually, they will be unlocked automatically after 10 seconds lock.lock(10, TimeUnit.SECONDS); // Wait for 100 seconds for locking and unlock automatically after 10 seconds of successful locking boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); ... lock.unlock();
5) Read write lock:
Redisson distributed reentrant read / write lock RReadWriteLock Java object based on Redis implements Java util. concurrent. locks. Readwritelock interface. Both read lock and write lock inherit RLock interface. Distributed reentrant read-write locks allow multiple read locks and one write lock to be locked at the same time.
RReadWriteLock rwlock = redisson.getReadWriteLock("anyRWLock"); // Most common usage rwlock.readLock().lock(); // or rwlock.writeLock().lock(); //In addition, Redisson also provides the parameter of leaseTime to specify the locking time through the locking method. After this time, the lock will be unlocked automatically. // Automatic unlocking after 10 seconds // There is no need to call the unlock method to unlock manually rwlock.readLock().lock(10, TimeUnit.SECONDS); // or rwlock.writeLock().lock(10, TimeUnit.SECONDS); // Try to lock, wait for 100 seconds at most, and unlock automatically 10 seconds after locking boolean res = rwlock.readLock().tryLock(100, 10, TimeUnit.SECONDS); // or boolean res = rwlock.writeLock().tryLock(100, 10, TimeUnit.SECONDS); ... lock.unlock();
6) Semaphore:
Redisson's distributed semaphore Java object RSemaphore based on Redis is similar to Java util. concurrent. Semaphore has similar interfaces and usage. It also provides asynchronous, Reactive and RxJava2 standard interfaces.
RSemaphore semaphore = redisson.getSemaphore("semaphore"); semaphore.acquire(); //or semaphore.acquireAsync(); semaphore.acquire(23); semaphore.tryAcquire(); //or semaphore.tryAcquireAsync(); semaphore.tryAcquire(23, TimeUnit.SECONDS); //or semaphore.tryAcquireAsync(23, TimeUnit.SECONDS); semaphore.release(10); semaphore.release(); //or semaphore.releaseAsync();
7) Expirable semaphore:
Redisson expirable semaphore based on Redis adds an expiration time for each signal based on the RSemaphore object. Each signal can be identified by an independent ID. when releasing, it can only be released by submitting this ID. It provides asynchronous, Reactive, and RxJava2 standard interfaces.
RPermitExpirableSemaphore semaphore = redisson.getPermitExpirableSemaphore("mySemaphore"); String permitId = semaphore.acquire(); // Get a signal, valid for only 2 seconds. String permitId = semaphore.acquire(2, TimeUnit.SECONDS); // ... semaphore.release(permitId);
8) Latch:
The Redisson distributed locking (CountDownLatch) Java object RCountDownLatch based on Redisson is similar to Java util. concurrent. CountDownLatch has similar interface and usage.
RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch"); latch.trySetCount(1); latch.await(); // In another thread or other JVM RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch"); latch.countDown();
9) Distributed AtomicLong:
RAtomicLong atomicLong = redisson.getAtomicLong("myAtomicLong"); atomicLong.set(3); atomicLong.incrementAndGet(); atomicLong.get();
10) Distributed BitSet:
RBitSet set = redisson.getBitSet("simpleBitset"); set.set(0, true); set.set(1812, false); set.clear(0); set.addAsync("e"); set.xor("anotherBitset");
11) Distributed Object:
RBucket<AnyObject> bucket = redisson.getBucket("anyObject"); bucket.set(new AnyObject(1)); AnyObject obj = bucket.get(); bucket.trySet(new AnyObject(3)); bucket.compareAndSet(new AnyObject(4), new AnyObject(5)); bucket.getAndSet(new AnyObject(6));
12) Distributed Set:
RSet<SomeObject> set = redisson.getSet("anySet"); set.add(new SomeObject()); set.remove(new SomeObject());
13) Distributed List:
RList<SomeObject> list = redisson.getList("anyList"); list.add(new SomeObject()); list.get(0); list.remove(new SomeObject());
14) Distributed Blocking Queue:
RBlockingQueue<SomeObject> queue = redisson.getBlockingQueue("anyQueue"); queue.offer(new SomeObject()); SomeObject obj = queue.peek(); SomeObject someObj = queue.poll(); SomeObject ob = queue.poll(10, TimeUnit.MINUTES);
15) Distributed Map:
RMap<String, SomeObject> map = redisson.getMap("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"); Future<SomeObject> putAsyncFuture = map.putAsync("321"); Future<Void> fastPutAsyncFuture = map.fastPutAsync("321"); map.fastPutAsync("321", new SomeObject()); map.fastRemoveAsync("321");
In addition, it also supports Multimap.
16)Map eviction:
At present, Redis does not have the function of clearing an entry in the Map after expiration. It can only empty all entries in the Map. Redistribution provides this functionality.
RMapCache<String, SomeObject> map = redisson.getMapCache("anyMap"); // ttl = 10 minutes, map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES); // ttl = 10 minutes, maxIdleTime = 10 seconds map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS); // ttl = 3 seconds map.putIfAbsent("key2", new SomeObject(), 3, TimeUnit.SECONDS); // ttl = 40 seconds, maxIdleTime = 10 seconds map.putIfAbsent("key2", new SomeObject(), 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS)