1.Redis Lock
使用场景
同步锁,让业务方法在锁设定的时间内是同步执行的
redisService.setIfAbsent
redisService.expire
@PostMapping("/update")
public MMHResponse saveOrUpdateMemberBaby(@RequestBody SaveOrUpdateMemberBabyForm form){
GlobalLock globalLock = null;
try {
globalLock = GlobalLockRedisImpl.getInstance(key);
globalLock.lock();
//TODO ...业务方法
return SuccessResponse.newInstance();
} catch (Exception e) {
logger.error("[ebiz-user-service][saveOrUpdateMemberBaby]操作失败,原因{}", StackTraceLogUtil.getStackTraceAsString(e));
return ErrorResponse.newInstance("操作失败");
} finally {
//释放锁
if (globalLock != null) {
globalLock.unlock();
}
}
}
不难看出,redis不参与业务逻辑代码,仅仅作一个定时的开发,保证在某个时间段内 业务代码不受干扰
我们再来看一下lock 方法
GlobalLock
/**
* <pre>
* Example 1: 强制获取锁,会阻塞, 超时失败会抛出异常
* GlobalLock lock = GlobalLockRedisImpl.getInstance("local key name")
* try{
* lock.lock(5);
* doSamething()
* } catch(GDSystemException e) {
* //获取锁异常
* } finally {
* lock.unlock();
* }
*
*
* Example 2: 尝试获取锁, 失败会直接返回false
* GlobalLock lock = ...;
* if (lock.tryLock()) {
* try {
* // manipulate protected state
* } finally {
* lock.unlock();
* }
* } else {
* // perform alternative actions
* }
* </pre>
*/
public interface GlobalLock { /**
* 申请加锁,此操作为阻塞操作,且不响应线程中断
* 超过指定时间会抛出异常,程序需要对异常处理, 最大锁住时间为1分钟
*
* @throws RuntimeException 在指定的时间内获取锁失败
*/
void lock(int timeout) throws RuntimeException; /**
* 申请加锁, 最大时间30秒
*
* @throws RuntimeException
*/
void lock() throws RuntimeException; /**
* Acquires the lock only if it is free at the time of invocation.
* <p>
* <p>Acquires the lock if it is available and returns immediately
* with the value {@code true}.
* If the lock is not available then this method will return
* immediately with the value {@code false}.
* <p>
* <p>A typical usage idiom for this method would be:
* <pre>
* Lock lock = ...;
* if (lock.tryLock()) {
* try {
* // manipulate protected state
* } finally {
* lock.unlock();
* }
* } else {
* // perform alternative actions
* }
* </pre>
* This usage ensures that the lock is unlocked if it was acquired, and
* doesn't try to unlock if the lock was not acquired.
*
* @return {@code true} if the lock was acquired and
* {@code false} otherwise
*/
boolean tryLock(); /**
* 释放锁
*/
void unlock(); }
GlobalLockRedisImpl
/**
* 基于redis实现的全局锁
*/
public class GlobalLockRedisImpl implements GlobalLock { private ILog logger = LogFactory.getLog(GlobalLockRedisImpl.class, LogBusinessModule.TRACE_LOG); private RedisService redisService; // timeout(ms)
private static final int TIME_OUT = 30; // private Jedis jedis;
private String key; // state flag
private volatile boolean locked = false; private static ConcurrentMap<String, GlobalLock> map = Maps.newConcurrentMap(); /**
* 构造函数
*
* @param key
*/
private GlobalLockRedisImpl(String key) {
this.key = "_LOCK_" + key;
this.redisService = (RedisService) MyApplicationContext.getBean("redisService");
} public static GlobalLock getInstance(String key) {
GlobalLock globalLock = map.get(key);
if (globalLock == null) {
map.put(key, new GlobalLockRedisImpl(key));
return map.get(key);
}
return globalLock;
} public boolean tryLock() {
long result = redisService.increment(key);
boolean success = result <= 1;
if (!success) {// 锁已被占用,等待释放
result = redisService.increment(key);
success = result <= 1;
}
if (success) {// 处理锁的自动释放
redisService.set(key, String.valueOf(result), TIME_OUT);
locked = true;
if (logger.isDebugEnabled()) {
logger.debug("尝试获取锁{}成功, 锁将在 {} 秒后释放", key, TIME_OUT);
}
}
return success;
} public void lock(int timeout) throws RuntimeException {
long nanoTime = System.nanoTime();
do {
if (redisService.setIfAbsent(key, key)) {
redisService.expire(key, 1, TimeUnit.MINUTES); //设定锁过期时间为1分钟
locked = true;
if (logger.isDebugEnabled()) {
logger.debug("get key: {} lock success! -- {} 毫秒", key, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - nanoTime));
}
return;
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while ((System.nanoTime() - nanoTime) < TimeUnit.SECONDS.toNanos(timeout));
throw new RuntimeException("获取锁超时, 消耗时间: " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - nanoTime) + "毫秒");
} public void lock() throws RuntimeException {
lock(TIME_OUT);
} public void unlock() {
if (locked) {
redisService.delete(key);
}
} }
public void lock() throws GDSystemException {
lock(30);
}
public void lock(int timeout) throws GDSystemException {
long nanoTime = System.nanoTime();
while(!redisService.setIfAbsent(this.key, this.key)) {
try {
Thread.sleep(300L);
} catch (InterruptedException var5) {
var5.printStackTrace();
}
if(System.nanoTime() - nanoTime >= TimeUnit.SECONDS.toNanos((long)timeout)) {
throw new GDSystemException("获取锁超时, 消耗时间: " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - nanoTime) + "毫秒");
}
}
this.redisService.expire(this.key,60, TimeUnit.SECONDS);
this.locked = true;
if(logger.isDebugEnabled()) {
logger.debug("get key: {} lock success! -- {} 毫秒", new Object[]{this.key, Long.valueOf(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - nanoTime))});
}
}
lock 默认你的时间30s,
redisService.setIfAbsent(this.key, this.key)
进一步来看setIfAbsent的源码:
public Boolean setIfAbsent(String key, Object value) {
return this.getRedisTemplate().opsForValue().setIfAbsent(key, value);
}
public Boolean setIfAbsent(K key, V value) {
final byte[] rawKey = this.rawKey(key);
final byte[] rawValue = this.rawValue(value);
return (Boolean)this.execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setNX(rawKey, rawValue);
}
}, true);
}
对 Redis setNX的这个方法,参考官方文档,判断key是否存在(1/0)
Return value
Integer reply, specifically:
1 if the key was set
0 if the key was not set
再往下看 redisService.expire 保证key 60s有效,足够执行业务代码,
执行往后,delete该key
1.Redis Lock的更多相关文章
- Redis Distributed lock
using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using ...
- python redis自带门神 lock 方法
redis 支持的数据结构比较丰富,自制一个锁也很方便,所以极少提到其原生锁的方法.但是在单机版redis的使用时,自带锁的使用还是非常方便的.自己有车还打啥滴滴顺风车是吧,本篇主要介绍redis-p ...
- redisLock redis分布式锁
redis-lock redis setnx cmmand java object condition queue 条件队列 retrycount 带有重试次数限制 object wait time ...
- redis实现分布式可重入锁
利用redis可以实现分布式锁,demo如下: /** * 保存每个线程独有的token */ private static ThreadLocal<String> tokenMap = ...
- 用redis实现分布式锁,秒杀案例(转)
分布式锁的简单实现代码: 需要的jar包: jedis-2.9.0.jar. commons-pool2-2.4.2.jar import java.util.List; import java.ut ...
- 基于 redis 的分布式锁实现 Distributed locks with Redis debug 排查错误
小结: 1. 锁的实现方式,按照应用的实现架构,可能会有以下几种类型: 如果处理程序是单进程多线程的,在 python下,就可以使用 threading 模块的 Lock 对象来限制对共享变量的同步访 ...
- Redis分布式锁的实现
前段时间,我在的项目组准备做一个类似美团外卖的拼手气红包[第X个领取的人红包最大],基本功能实现后,就要考虑这一操作在短时间内多个用户争抢同一资源的并发问题了,类似于很多应用如淘宝.京东的秒杀活动场景 ...
- 【Redis使用系列】使用Redis做防止重复提交
前言 在平时的开发中我们都需要处理重复提交的问题,避免业务出错或者产生脏数据,虽然可以通过前端控制但这并不是可以完全避免,最好的方式还是前后端均进行控制,这样的话就可以更有效,尽可能全面的去减少错误的 ...
- Redis实现分布式锁1
Jedis结合setNX方法实现分布式锁 public boolean lock(String key, int exprie) { try { exprie = exprie <= 0 ? 6 ...
随机推荐
- Java Mail 发送带有附件的邮件
1.小编用的是163邮箱发送邮件,所以要先登录163邮箱开启POP3/SMTP/IMAP服务方法: 2.下载所需的java-mail 包 https://maven.java.net/content/ ...
- 爬虫之图片懒加载技术、selenium工具与PhantomJS无头浏览器
图片懒加载技术 selenium爬虫简单使用 2.1 selenium简介 2.2 selenium安装 2.3 selenium简单使用 2.3.1 selenium使用案例 2.3.2 selen ...
- 【MySQL】如何解决分库分表遇到的自增主键的问题?
雪花算法 Redis生成主键
- python-基站位置查询
本文采用的接口是聚合数据提供的 python2.7环境,3.x环境试了下好像不支持,获取位置信息为空 如下为运用代码: #coding=utf-8 ''' Created on 2019年9月18日 ...
- SimpleAuthenticationInfo的参数
SimpleAuthenticationInfo的参数 仅供个人参考,以及学习记录.SimpleAuthenticationInfo authenticationInfo = new SimpleAu ...
- js学习零碎只是汇总
虽然JS是弱类型语言,但也有变量声明,作用域(局部和全局). 1.基础输出语句: alert();以弹框的方式将括号内的信息输出到页面上,有一个确定按钮. console.log();常 ...
- Flexible 应用
Flexibl.js 为我们做了一项工作,媒体查询工作,节约了许多操作 举个例子,移动端的页面设计稿是750px,我们自己换算rem单位,比如我想把屏幕划分为15等份,我就750/15=50,然后用所 ...
- JUC整理笔记三之测试工具jcstress
并发测试工具Jcstress使用教程 Jcstress 全称 Java Concurrency Stress,是一种并发压力测试工具,可以帮助研究JVM.java类库和硬件中并发的正确性. Wiki地 ...
- Android_AndroidX简介&Junit4
AndroidX简介: Android 9.0(API level 28)发布时,AndroidX也作为一个新的支持库发布出来了.AndroidX时Jetpack的一部分,它包含了现有的支持库和最新的 ...
- [自动化-脚本]001.自动领淘金币:Anyweb模拟操作
通过模拟手工操作的方法领取淘金币.该方法万能且通用,有能力的还可以自行修改脚本. 工具 软件下载 anywebscript.com 方法/步骤 1.安装软件如图所示 2.设置脚本: (1)进入网站:[ ...