Redis Java-based implementation of distributed lock (SpringBoot)

Foreword

Distributed Lock, in fact, the principle is that multiple machines, to a competition for resources, who is fighting for success, then whoever holds this lock, then subsequent to execution of business logic, after the implementation, the lock released.

It can be achieved through various channels distributed lock, such as the use of a database (mysql, etc.), insert a record (unique index), who successfully inserted, whoever holds the lock; distributed lock can also be achieved by zookeeper, who successfully created node , whoever holds the lock. This article describes a distributed lock is achieved by redis.

As used herein, RedisTemplate springboot provided by operating redis, can refer to my previous article [fast learning springboot] 13. String data structure of the operation redis , where the use of RedisTemplate to operate redis introduced. Of course, also can be used directly jedis to operate redis, we can refer to jedis documentation, use is much the same.

Steps to implement a distributed lock

The first step: (set does not exist) by way setnx redis, and a key to the redis set with an expiration time, if set up, then get distributed lock. Here set the expiration time, is to prevent the release of the lock at the time of abnormal cause can not afford to release the lock.

Step Two: After the completion of the implementation of business operations, remove the lock.

achieve

Create a new DistributedLock.class, injection StringRedisTemplate.

@Component
public class DistributedLock {
 @Autowired
 private StringRedisTemplate redisTemplate;
}
复制代码

Get lock

/**
 * 获得锁
 */
 public boolean getLock(String lockId, long millisecond) {
 Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, "lock",
 millisecond, TimeUnit.MILLISECONDS);
 return success != null && success;
 }
复制代码

setIfAbsent method, when the key is not present is provided, and the method may set an expiration time of the key. The method corresponds to redis native commands is:

SET lockId content PX millisecond NX 
复制代码

As for how much to set the expiration time is right, this is not conclusive, really needs to be measured in terms of business scenarios.

Release the lock

When the service logic has been processed, the lock manually released.

 public void releaseLock(String lockId) {
 redisTemplate.delete(lockId);
 }
复制代码

Release the lock operation is relatively simple, direct delete key can be set before. In fact, based on the way redis implementation of distributed lock, the lock is released when it is released there is risk of failure (such as what network jitter), which is why when you need to set the lock of the reasons set expiration time can be prevented when abnormal, the lock will automatically disappear. At the same time, we can also increase the retry mechanism after several failures.

test

Create a BusinessTask.java, code is as follows:

@Component
public class BusinessTask {
 private final static String LOCK_ID = "happyjava";
 @Autowired
 DistributedLock distributedLock;
 @Scheduled(cron = "0/10 * * * * ? ")
 public void doSomething() {
 boolean lock = distributedLock.getLock(LOCK_ID, 10 * 1000);
 if (lock) {
 System.out.println("执行任务");
 distributedLock.releaseLock(LOCK_ID);
 } else {
 System.out.println("没有抢到锁");
 }
 }
}
复制代码

This uses notes springboot Scheduled to achieve regular tasks, the cron expression mean every 10 seconds, perform a task, and then we start the project twice, a period of observation results of the implementation:

The first springboot tasks:

The second springboot tasks:

Two tasks in alternate mission proved that only one application holds a lock.

to sum up

This article describes how to use Java code (springboot of restTemplate) to achieve Redis distributed lock for locking and unlocking were also given sample code. In fact, we can also try using a distributed lock Redisson realize that this is the official Java components Redis, the subsequent re-introduce it.

Reproduced in: https: //juejin.im/post/5d07a089518825664b6ce28a

Guess you like

Origin blog.csdn.net/weixin_34268610/article/details/93181305