分布式锁使用supplier实现,将delete封装在其中
redisLockService.tryLock(key, "1",
() -> “自己要实现的函数”, 3);
public <T, R extends Exception> T tryLock(String key, String value, Supplier<T> supplier, int defaultExpireTimes) throws R {
if (redisGateway.setNx(value, defaultExpire, key)) {
try {
return supplier.get();
} finally {
redisGateway.delete(key);
}
}
throw new ServiceException(key + "获取锁失败");
}
/**
* setnx,使用多个参数构成key,按顺序传入
*
* @param value
* @param expireSeconds
* @param keyParams
* @return
*/
public boolean setNx(Object value, int expireSeconds, Object... keyParams) {
String key = function(keyParams);
return redisStoreClient.setnx(key, value, expireSeconds);
}