1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
| package com.guozhe.core.service.impl;
import com.github.rholder.retry.*; import com.google.common.base.Joiner; import com.guozhe.core.exception.AssetCommonException; import com.guozhe.core.utils.CommonPreconditions; import com.guozhe.core.utils.CommonUtil; import com.guozhe.core.utils.UUIDUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate;
import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit;
@Slf4j public class RedisLock {
static final String REDIS_LOCK_PREFIX = "CORE_LOCK";
static final String REDIS_DEFAULT_SPLIT = ":";
private static final int TTL_NO_EXPIRE_RESPONSE = -1;
private final Retryer<Boolean> retryer;
private final int redisLockExpireSeconds;
private final RedisTemplate<String, String> redisTemplate;
RedisLock(RedisTemplate<String, String> redisTemplate, int redisLockExpireSeconds) { this.redisTemplate = redisTemplate; this.redisLockExpireSeconds = redisLockExpireSeconds; this.retryer = getRetryer((this.redisLockExpireSeconds * 1000) / 100, 100L); }
public <T> T lockAndCall(Callable<T> beforeLock, Callable<T> beforeBizCalled, Callable<T> bizCallable, String businessName, String key) { if (CommonUtil.isNotNull(beforeLock)) { T result = call(beforeLock); if (CommonUtil.isNotNull(result)) { return result; } } final String uuid = UUIDUtils.getUUID(); retryLock(businessName, key, uuid); return lockSuccessDoBiz(beforeBizCalled, bizCallable, businessName, key, uuid); }
<T> T lockAndCallNoRetry(Callable<T> beforeLock, Callable<T> beforeBizCalled, Callable<T> bizCallable, String businessName, String key) { if (CommonUtil.isNotNull(beforeLock)) { T result = call(beforeLock); if (CommonUtil.isNotNull(result)) { return result; } } final String uuid = UUIDUtils.getUUID(); if (tryLock(businessName, key, uuid)) { return lockSuccessDoBiz(beforeBizCalled, bizCallable, businessName, key, uuid); } return null; }
private <T> T lockSuccessDoBiz(Callable<T> beforeBizCalled, Callable<T> bizCallable, String businessName, String key, String value) { try { if (CommonUtil.isNotNull(beforeBizCalled)) { T call = beforeBizCalled.call(); if (CommonUtil.isNotNull(call)) { return call; } } CommonPreconditions.checkArgument(CommonUtil.isNotNull(bizCallable), "businessName=%s,key=%s业务处理逻辑为null", businessName, key); return bizCallable.call(); } catch (Exception e) { throw new AssetCommonException(e); } finally { log.info("{}业务处理完成,解锁key={},value={}", businessName, key, value); unlocked(key, value); } }
private <T> T call(Callable<T> callable) { try { return callable.call(); } catch (Exception e) { throw new AssetCommonException(e); } }
static byte[] getRedisKey(String key) { return getRedisKeyString(key).getBytes(); }
static String getRedisKeyString(String first, String... rest) { return Joiner.on(REDIS_DEFAULT_SPLIT).join(REDIS_LOCK_PREFIX, first, rest); }
private void unlocked(String key, String value) { final byte[] redisKey = getRedisKey(key); redisTemplate.execute((RedisCallback<Boolean>) connection -> { byte[] bytes = connection.get(redisKey); if (Arrays.equals(value.getBytes(), bytes)) { connection.del(redisKey); } return null; }); }
private void retryLock(String businessName, String key, String value) { try { retryer.call(() -> tryLock(businessName, key, value)); } catch (RetryException e) { throw new AssetCommonException(String.format("业务%s,key=%s正在处理中,请稍后重试", businessName, key)); } catch (ExecutionException e) { log.error("businessName={},key={}执行redis加锁异常 errorMsg={}", businessName, key, e.getMessage(), e); } }
private boolean tryLock(String businessName, String key, String value) { return tryLock(businessName, key, value, this.redisTemplate, this.redisLockExpireSeconds); }
private static boolean tryLock(String businessName, String key, String value, RedisTemplate<String, String> redisTemplate, long redisLockExpireSeconds) { final byte[] redisKey = getRedisKey(key); return redisTemplate.execute((RedisCallback<Boolean>) connection -> { boolean result = connection.setNX(redisKey, value.getBytes()); if (result) { log.info("businessName={} key={} value={},设置锁的失效时间={}s", businessName, key, value, redisLockExpireSeconds); connection.expire(redisKey, redisLockExpireSeconds); } else {
if (TTL_NO_EXPIRE_RESPONSE == connection.ttl(redisKey)) { connection.expire(redisKey, redisLockExpireSeconds); } } return result; }); }
public Retryer<Boolean> getRetryer(int retryTimes, long fixedWaitTime) {
return RetryerBuilder.<Boolean>newBuilder() .withWaitStrategy(WaitStrategies.fixedWait(fixedWaitTime, TimeUnit.MILLISECONDS)) .withStopStrategy(StopStrategies.stopAfterAttempt(retryTimes)) .retryIfResult(aBoolean -> aBoolean == null || !aBoolean).build(); }
}
|