正确方法
加锁:
public 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"; /** * 尝试获取分布式锁 * @param jedis Redis客户端 * @param lockKey 锁 * @param requestId 请求标识 * @param expireTime 超期时间 * @return 是否获取成功 */ 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; }
释放锁:
public class RedisTool { private static final Long RELEASE_SUCCESS = 1L; /** * 释放分布式锁 * @param jedis Redis客户端 * @param lockKey 锁 * @param requestId 请求标识 * @return 是否释放成功 */ 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; } } 参考:https://mp.weixin.qq.com/s/qJK61ew0kCExvXrqb7-RSg https://xiaomi-info.github.io/2019/12/17/redis-distributed-lock/ -----------下列方法错误:如果在setnx和expire 中间服务挂掉则出现问题------------ 1.使用setNx做分布式锁:setnx只能设置一次值,第二次会设置失败 ```java public Boolean setSecondTime(String key, String value, Long secondTime) { try { boolean flag= client.setNX(key, value); client.expire(key, secondTime, TimeUnit.SECONDS); } catch (Exception e) { log.error("jimdbservice setSecondTime", e); } return flag; }
try { if (boardJimdbService.setSecondTime(Sale_Task_key, "111", 8L)) { //TODO } } catch (Exception e) { } finally { boardJimdbService.del(Sale_Task_key); }