当前位置:网站首页>Implementation of redis distributed lock

Implementation of redis distributed lock

2022-07-04 20:44:00 The great man ate a Kun on the day he was alive

1 Import jedis rely on

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version> Just fill in the version </version>
</dependency>

2 Lock && Unlock

@Component
class RedisTool {
private static final String LOCK_SUCCESS = “OK”;
private static final String SET_IF_NOT_EXIST = “NX”;
private static final String SET_WITH_EXPIRE_TIME = “PX”;
/**
* Try to get distributed lock
* @param jedis Redis client
* @param lockKey lock
* @param requestId The request id
* @param expireTime Beyond the time
* @return Success or failure
*/

public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {

    String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);

    if (LOCK_SUCCESS.equals(result)) {
        return true;
    }
    return false;

}

/**
 *  Release distributed lock 
 * @param jedis Redis client 
 * @param lockKey  lock 
 * @param requestId  The request id 
 * @return  Whether to release successfully 
 */
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {

    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));

    if (RELEASE_SUCCESS.equals(result)) {
        return true;
    }
    return false;

}

}

3 This is simpler , Official recommended use reddsion Establish distributed locks

4 There are some problems I'll add later , Throw it out first , And provide some solutions , If there is any deficiency , Welcome to spray

1. The expiration time is set here , But if two services make a request one after the other ,a The service is stuck , The lock has expired ,B Service started , however B The lock opened by the service is A The service is off ,B The service is unlocked ,A The service doesn't close its own lock , therefore ....
For this kind of problem It uses requestId To solve
2 Suppose that due to business needs , Without setting the expiration time , Service to hang , restart This lock , Lock the loneliness . You can use redis It's sentinel mode
3 hypothesis redis Hang up , Lock failure , The service is close to streaking , I don't know if the data is dirty , For sites , Use transaction rollback appropriately

原网站

版权声明
本文为[The great man ate a Kun on the day he was alive]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041903344154.html