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 ...
随机推荐
- flask之request
from flask import Flask, render_template, redirect, jsonify, send_file, request, session app = Flask ...
- Blazor WebAssembly 3.2 正式发布
5月 20日,微软 发布了 Blazor WebAssembly 3.2(https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0- ...
- Solr-常见问题汇总(持续更新)
本文主要记录solr使用中遇到的一些常见问题及命令 关于solrConfig.xml的配置博客:https://blog.csdn.net/yuh_LLllccy/article/details/88 ...
- Jmeter(二) - 从入门到精通 - 创建测试计划(Test Plan)(详解教程)
1.简介 上一篇中宏哥已经教你把JMeter的测试环境搭建起来了,那么这一篇我们就将JMeter启动起来,一睹其芳容,首先宏哥给大家介绍一下如何来创建一个测试计划(Test Plan). 2.创建一个 ...
- hdu4757 可持续字典树
Tree Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 102400/102400 K (Java/Others)Total Sub ...
- 博客管理与文章发布系统-第三方模块及其用法Part1
写个帖子记录一下自己写的第一个express完整项目. 所需第三方模块及其用法. 一.先把所需文件和准备工作写一下 写项目前的准备 1.创建所需文件夹 public 静态资源 model 数据库操作 ...
- 集合框架之ArrayList -Java
ArrayList 1.与数组的区别 如果要存放多个对象,可以使用数组,但是数组会有长度的限制,会出现不够用或者是浪费的情况. 为了解决数组的局限性引入了容器的概念,最常用的容器就是ArrayList ...
- C#中方法的静态和非静态
在代码中,给方法加上static就成为了一个静态的方法,然而静态方法是隶属于类的,由类名点出来! 不给方法加static就是一个非静态方法,非静态的方法,是隶属于对象的,需要把类实例化之后,用对象名去 ...
- Spring_自动装配 & bean之间的关系 & bean的作用域
1.自动装配 beans-autowire.xml <?xml version="1.0" encoding="UTF-8"?> <beans ...
- R语言入门二
一.R语言应知常用函数 1.getwd() 函数:获取工作目录(同eclipse设置workspace类似),直接在R软件中使用,如下图: 2.setwd(dir=”工作目录”) 函数:设置R软件RS ...