代码如下:
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class RedisTemplateUtil<K,V,HK,HV> {
@Autowired
private RedisTemplate<K,V> redisTemplate;
public boolean getDistributeLock(K lockKey,long timeout) {
boolean result = false;
try {
ValueOperations<K, V> operations = redisTemplate.opsForValue();
result = operations.setIfAbsent(lockKey,null);
redisTemplate.expire(lockKey,timeout,TimeUnit.SECONDS);
if (result) {
log.info("已获取到{}对应的锁!", lockKey);
}
}
catch (Exception ex) {
redisTemplate.expire(lockKey,timeout,TimeUnit.SECONDS);
log.error("获取redis 分布式锁发生了异常,{}",ExceptionUtils.getStackTrace(ex));
}
return result;
}
}
string 的setIfAbsent 方法还是调用的setNX方法。setNX 只有在键不存在的时候,才会对键进行设置操作。
这里为了防止如果setIfAbsent 方法发生了异常,但是键没有去设置失效时间。在catch中也加入了设置失效时间的操作。
这么写还是有问题的,在一些极端场景下还是会出现问题。
如果用redis实现分布式锁的话,还是用redission的set方法实现。
redission的Rlock 继承了ReentrantLock。可以向lock一样去实现,非常的方便。
类似实现代码如下:
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(inventory, inventory, 10L, SECONDS, linkedBlockingQueue);
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
final RedissonClient client = Redisson.create(config);
final RLock lock = client.getLock("lock1");
for (int i = 0; i <= 10; i++) {
threadPoolExecutor.execute(new Runnable() {
public void run() {
lock.lock();
//执行业务逻辑
System.out.println(i);
lock.unlock();
}
});
}
除了redis 还有zookeeper也可以实现分布式锁。
可以使用Curstor客户端去实现