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

这么写还是有问题的,在一些极端场景下还是会出现问题。

如果用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客户端去实现

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值