ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Redis分布式锁

2020-02-22 14:04:35  阅读:240  来源: 互联网

标签:String Redis 分布式 time import oldTime stringRedisTemplate productId


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

例如:商品秒杀场景下,商品库存的处理,即可引入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());
}
}
}

标签:String,Redis,分布式,time,import,oldTime,stringRedisTemplate,productId
来源: https://www.cnblogs.com/zhangdongfang/p/12345155.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有