This article was adapted from: Lebyte

Redisson

For more Java related information, please follow the public account “LeByte” to send: 999

Redis distributed locks

The Java version of the distributed locking framework is Redisson.

What is a Redisson?

Redisson is the easiest and easiest way to use Redis if you’re already using it.

The goal of Redisson is to promote the Separation of Concern for Redisso that users can focus more on business logic.

Redisson is a Java in-memory Data Grid based on Redis.

Second, integrate Redisson

Spring Boot integration Redisson has two options:

This article shows you how to integrate Redisson programmatically.

2.1 Introducing Maven dependencies

Redisson’s Maven dependency is introduced in the passjava-question microservice pom.xml.

2.2 Customizing Configuration Classes

The following code is the configuration of single-node Redis.

2.3 Testing configuration classes

Create a new unit test method.

We run the test method and print out the redissonClient

Distributed reentrant lock

3.1 Reentrant lock test

Based on Redis Redisson distributed reentrant Lock RLockJava object implements the Java. Util. Concurrent. The locks. Lock interface. It also provides Async, Reactive and RxJava2 standard interfaces.

We used passJava, an open source project, to test two points of the reentrant lock:

3.1.1 Verification one: Does a reentrant lock block?

In order to verify the above two points, I wrote a demo program: the code flow is to set wukong-lock, lock, print the thread ID, wait 10 seconds to release the lock, and finally return the response: “test lock OK”.

Verify the first point and test the lock preemption with two HTTP requests.

Requested URL:

The corresponding thread ID for the first thread is 86. After 10 seconds, the lock is released. In the meantime, the second thread needs to wait for the lock to be released.

After the first thread releases the lock, the second thread acquires it, and after 10 seconds, the lock is released.

I drew a flow chart to help you understand. As shown below:

It follows that Redisson’s reentrant lock blocks other threads and waits for them to release.

3.1.2 Verification 2: When the service stops, will the lock be released?

If the service stops while thread A is waiting, will the lock be released? If not released, it becomes a deadlock, blocking other threads from acquiring the lock.

Let’s first take A look at the result queried by Redis client after thread A acquired the lock, as shown in the figure below:

Wukong-lock has a value, and you can see that the TTL is getting smaller and smaller, indicating that Wukong-lock has its own expiration time.

After 30 seconds of observation, Wukong-lock expired and disappeared. Note After Redisson is stopped, the lock occupied by Redisson is automatically released.

So how does that work? Here comes the concept of a guard dog.

3.2 Principle of watchdog

If the Redisson node that stores the distributed lock goes down and the lock happens to be in the locked state, the lock will become locked. To prevent this from happening, Redisson internally provides a lock watchdog that continuously extends the lifetime of the lock before the Redisson instance is closed.

By default, the watchdog check lock timeout time is 30 seconds, but can be by modified Config. LockWatchdogTimeout to specify separately.

If we do not specify a lock timeout, use 30 seconds as the default watchdog time. Once the lock is successfully captured, a timed task will be initiated to reset the lock expiration time to 30 seconds every 10 seconds.

As shown below:

3.3 Setting the Lock Expiration Time

We can also set an expiration time for locks to unlock automatically.

Set the lock to expire automatically after 8 seconds, as shown below.

If the service execution time exceeds 8 seconds, manually releasing the lock will prompt an error, as shown in the following figure:

Therefore, if the automatic expiration time of the lock is set, the service execution time must be shorter than the automatic expiration time of the lock; otherwise, an error will be reported.

Four, king plan

Because Redisson isso powerful, the solution for implementing distributed locking isso simple that it is called the king solution.

The schematic diagram is as follows:

The code looks like this:

Compared to the previous Redis scheme, it is much simpler.

Here are some of Redisson’s other distributed locks that you will use in future projects.

Distributed read/write lock

Based on Redis Redisson distributed re-entrant read-write lock RReadWriteLock Java object implements the Java. Util. Concurrent. The locks. ReadWriteLock interface. Read and write locks inherit the RLock interface.

A write lock is an exclusive lock (mutex) and a read lock is a shared lock.

Example code is as follows:

In addition, Redisson provides the leaseTime parameter to specify the lock time through the lock method. After this time, the lock unlocks automatically.

Distributed semaphores

Based on Redis Redisson distributed signal (Semaphore) Java objects RSemaphore adopted with Java. Util. Concurrent. The Semaphore similar interface and usage. It also provides Async, Reactive and RxJava2 standard interfaces.

In terms of semaphore use you can imagine a scenario where you have three parking Spaces, and when three parking Spaces are full, other cars stop. Parking space can be compared to a signal, now there are three signals, stop a car, use a signal, the car is to release a signal.

We use Redisson to illustrate the above parking space scenario.

Define a way to occupy a parking space:

Define another way to leave a parking space:

For simplicity, I used the Redis client to add a key: “park” with a value equal to 3, which means the semaphore is park, and there are three values in total.

Then use Postman to send park a request to occupy a parking space.

Then check the value of park in the Redis client and find that it has been changed to 2. After two more calls, park is found to be 0. When the fourth call is made, the request is always waiting, indicating that the parking space is not enough. If you want to avoid blocking, you can use tryAcquire or tryAcquireAsync.

When we call the method of leaving the parking space, the value of park changes to 1, indicating that there is one parking space left.

Note: The semaphore release operation is repeated and the remaining semaphore increases, instead of being capped at 3.

Other distributed locks:

Thank you for your recognition and support, xiaobian will continue to forward “LeByte” quality articles