標籤:redis分布式 nts default col 分布 port ESS The ted
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 zad12 * @create 2018-09-14 13:5813 */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 }
Redis分布式鎖