Redis using Java Distributed Lock

You Rui java learning by sharing lessons, learn about how to implement it and distributed lock More information in the project!

What is a distributed lock?

In a multithreaded program, different threads may need to access the same resources. However, all the threads at the same time allow access to resources may lead to a race condition errors and other unexpected behavior.

To ensure that no two threads can access the same resource at the same time, and ensure predictable order to manipulate resources, programmers use a mechanism called lock. Each thread acquires the lock first, then to manipulate resources, and finally to the other thread releases the lock.

In Java, a variety of reasons, the lock object is typically more flexible than the sync blocks used. First, Lock API can be operated in different ways, but completely contained in a sync block process.
In addition, if the thread is blocked, you can not access the synchronized block. Use Lock, the thread will only acquire a lock when available. This greatly reduces the time the waiting thread. In addition, when a thread is waiting, you can call a method to interrupt the thread, when the thread is waiting to acquire sync block, which is impossible.

Distributed locking means you not only need to consider multiple threads or processes, but also need to consider the different clients running on different computers. These separate server must be coordinated to ensure that any one of them in the use of resources at any given time.

Lock tool is based on a distributed Java Redis

Redisson frame is a Java-based Redis memory data grid, it may provide for the need to perform a plurality of objects distributed locking programmer. Below, we will discuss the differences between each option and.

1. Lock

RLock interface java.util.concurrent.locks.Lock interfaces in Java. This is a reentrant lock, which means multiple threads can be locked resources. A counter variable tracking lock request is executed many times. Once the thread issues unlock request and enough counter reaches zero, the resource will be released.

The following simple code example demonstrates how to create and initialize Lock in Redisson in:

RLock lock = redisson.getLock("anyLock");
// Most familiar locking method
lock.lock();
try {
  ...
} finally {
  lock.unlock();
}

If the acquired instance crashes Redisson this lock, the lock may be acquired in this state permanently suspended. Extend the expiration time of the lock To avoid this situation, Redisson maintains a lock "watchdog", the "watchdog" will still be active in Redisson instance holding the lock. By default, this lock watchdog timeout to 30 seconds. You can change this limit by Config.lockWatchdogTimeout setting.

Redisson leaseTime also allows you to specify parameters when obtaining a lease. After a specified time interval, the lock is automatically released:

// Acquire lock and release it automatically after 10 seconds
// if unlock method hasn't been invoked
lock.lock(10, TimeUnit.SECONDS);
// Wait for 100 seconds and automatically unlock it after 10 seconds
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {
   try {
     ...
   } finally {
       lock.unlock();
   }
}

Redisson also provides asynchronous / response / rxjava2 Lock interface objects:

RLock lock = redisson.getLock("anyLock");
lock.lockAsync();
...
// Reactive Stream (Spring Project Reactor implementation)
RLockReactive lock = redissonReactive.getLock("anyLock");
Mono<Void> res = lock.lock();
...
// Reactive Stream (RxJava2 implementation)
RLockReactive lock = redissonRx.getLock("anyLock");
Flowable<Void> res = lock.lock();
...

Since RLock realized the Lock interface, so only those with thread lock to unlock resources. Otherwise, any attempt will encounter IllegalMonitorStateException.

2. FairLock

Like its cousin RLock, RFairLock also realized java.util.concurrent.locks.Lock interface. By using FairLock, you can access to resources to ensure that the thread in the order requested resource (i.e., `` FIFO 'queue). Before unlocking resources for the next thread in the queue, Redisson would have been dead five seconds to restart the thread.

And RLocks as create and start FairLock is a simple process:

RLock lock = redisson.getFairLock("anyLock");
lock.lock();
try {
  ...
} catch {
  lock.unlock();
}
  1. ReadWriteLock

    Redisson of RReadWriteLock achieved java.util.concurrent.locks.ReadWriteLock interface. In Java, the read / write lock is actually a combination of two locks: a read-only locks may have simultaneously by multiple threads, but can only write locks once owned by a thread.

Method to create and initialize RReadWriteLock as follows:

RReadWriteLock rwlock = redisson.getReadWriteLock("anyRWLock");
rwlock.readLock().lock();
try {
  ...
} finally {
  rwlock.readLock().lock();
}
rwlock.writeLock().lock();
try {
  ...
} finally {
  rwlock.writeLock().lock();
}

4. RedLock

RedissonRedLock object implements Redlock locking algorithms to the distributed lock with Redis used with:

RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
try {
  ...
} finally {
   lock.unlock();
}

In Redlock algorithm, we have many independent Redis master node on a separate computer or virtual machine. The algorithm tries to use the same key names and values ​​of the random sequence to acquire the lock for each instance these examples. Only when the client is able to effectively lock than the total time faster access to the lock from most instances, it acquires the lock.

5. Multi-Lock

RedissonMultiLock plurality of individual objects can be combined together RLock Examples and managed as a single entity:

RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
lock.lock();
try {
  ...
} finally {
  lock.unlock();
}

As we have seen in the above example above, each object may belong to different RLock Redisson instances. In turn, this may be connected to other Redis database.

in conclusion

In this article, we discuss the Redisson framework for Java developers can be used on top of Redis database to perform a number of different tools distributed lock: Lock, FairLock, ReadWriteLock, RedLock and MultiLock. For more information Redisson in distributed computing, please follow the Wiki project on GitHub.

Guess you like

Origin blog.51cto.com/14634606/2462682