Redis分布式锁

应用场景:高并发、分布式应用下,要对部分代码块实现线程安全。

例如:商品秒杀场景下,商品库存的处理,即可引入Redis分布式锁。

优点:a.可实现更细粒度锁控制,对每个商品进行加锁,而不是正常扣库存代码块。b.支持分布式应用部署

1.安装部署好Redis

参见:https://www.cnblogs.com/zhangdongfang/p/11810899.html

2.工程pom引入Redis

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

3.RedisLock实现

package com.zdf.sell.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


/**
* 分布式锁
*/
@Component
@Slf4j
public class RedisLock {

@Autowired
private StringRedisTemplate stringRedisTemplate;

/**
* 以商品id和时间加锁
* @param productId 产品id
* @param time 到期时间 毫秒
* @return      true 获取锁成功,false 失败
*/
public boolean lock(String productId,String time){
//对应redis setnx命令:设置成功返回1,失败0;setIfAbsent 成功true
if (stringRedisTemplate.opsForValue().setIfAbsent(productId,time)){
return true;
}
/**
* 同样的产品id,若时间超时,则可以获取该产品的锁
*/
//1.获取产品之前的 锁 时间
String oldTime = stringRedisTemplate.opsForValue().get(productId);
//2.锁超时
if (StringUtils.isNotBlank(oldTime) && (System.currentTimeMillis() > Long.parseLong(oldTime))){
//获取之前锁时间,并设置新超时时间。再校验超时时间
String oldTime2 = stringRedisTemplate.opsForValue().getAndSet(productId, String.valueOf(time));
if (oldTime.equals(oldTime2)){
return true;
}
}
return false;
}

/**
* 释放锁
* 产品id和时间 共同来确认释放锁
* @param productId
* @param time
*/
public void unlock(String productId,String time){
try{
String oldTime = stringRedisTemplate.opsForValue().get(productId);
if(StringUtils.isNotBlank(oldTime) && oldTime.equals(time)){
stringRedisTemplate.delete(productId);
}
}catch (Exception e){
log.error("unlock Exception",e.getCause());
}
}
}
posted @ 2020-02-22 13:57  Melek  阅读(165)  评论(0编辑  收藏  举报