PS:参考文献讲得深入浅出,将来龙去脉都讲清楚了,非常值得一看
1 package com.zad.jedis;
2
3 import redis.clients.jedis.Jedis;
4
5 import java.util.Collections;
6
7 /**
8 * 描述:
9 * 分布式锁
10 *
11 * @author zad
12 * @create 2018-09-14 13:58
13 */
14 public class Distributed {
15 private static final String LOCK_SUCCESS = "OK";
16 private static final String SET_IF_NOT_EXIST = "NX";
17 private static final String SET_WITH_EXPIRE_TIME = "PX";
18 private static final Integer RELEASE_SUCCESS = 1;
19 private static final Integer DEFAULT_TIME = 5;
20
21 /**
22 * 尝试获取分布式锁
23 *
24 * @param jedis Redis客户端
25 * @param lockKey 锁
26 * @param requestId 请求标识
27 * @return 是否获取成功
28 */
29 public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId) {
30
31 String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, DEFAULT_TIME);
32
33 if (LOCK_SUCCESS.equals(result)) {
34 return true;
35 }
36 return false;
37
38 }
39
40
41 /**
42 * 尝试获取分布式锁
43 *
44 * @param jedis Redis客户端
45 * @param lockKey 锁
46 * @param requestId 请求标识
47 * @param expireTime 超期时间
48 * @return 是否获取成功
49 */
50 public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
51
52 String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
53
54 if (LOCK_SUCCESS.equals(result)) {
55 return true;
56 }
57 return false;
58
59 }
60
61 /**
62 * 释放分布式锁
63 *
64 * @param jedis Redis客户端
65 * @param lockKey 锁
66 * @param requestId 请求标识
67 * @return 是否释放成功
68 */
69 public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
70
71 String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
72 Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
73
74 if (RELEASE_SUCCESS.equals(result)) {
75 return true;
76 }
77 return false;
78
79 }
80 }
参考资料: https://wudashan.cn/2017/10/23/Redis-Distributed-Lock-Implement/
PS:参考文献讲得深入浅出,将来龙去脉都讲清楚了,非常值得一看