Distributed systems are cross-vm, and locks for the JVM do not work, so distributed locks are required.

The requirements are:

1. Multiple processes visible, otherwise how to mark

2. To avoid deadlocks is to ensure that locks can be released

3. The exclusive

4. How to rectify server downtime

There are many ways to implement it, and there are many things independent of Java services, such as Redis, databases, zooKeeper….

Briefly record a method implemented using Redis.

Setnx aa bb: setnx aa bb: setnx aa bb: setnx aa BB: setnx To avoid deadlocks, you can set an expiration date for the key, which is automatically deleted. 4

It doesn’t seem right. There’s something wrong with setting a key-value randomly

Why? For example, if process A executes and obtains the lock, it takes A long time to execute, but the lock is deleted when the time is up, process B obtains the lock and starts to execute, then process A finishes executing, runs del to delete the lock, and then process C obtains the lock again. There is a problem, please do not delete the lock is not your own, so you can set your own thread Id, AA thread information, each time before deleting is not your own.

Again, this lock is not a reentrant lock and should use a hash structure

Key AA Indicates the number of times of thread information. Del can be obtained only when the number is reduced to 0

The problem is that your logic of judgment is not atomic

I think we can change the logic to lua script execution

It turns out Redission already exists

@Autowired private RedissonClient redissonClient; Public void test() {RLock lock = redissonClient.getLock("aa"); RLock = redissonClient.getLock("aa"); Boolean isLock = lock.tryLock(); // Determine whether to obtain the lock if (! IsLock) {// get failed return; } try {} catch (InterruptedException e) {} finally {// Unlock lock.unlock(); }}Copy the code