使用redisTemplate简单实现分布式锁

代码如下:

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中也加入了设置失效时间的操作。

发布了8 篇原创文章 · 获赞 0 · 访问量 316

猜你喜欢

转载自blog.csdn.net/yancun93/article/details/104051345
今日推荐