分布式锁之三:Redlock实现分布式锁
之前写过一篇文章《如何在springcloud分布式系统中实现分布式锁?》,由于自己仅仅是阅读了相关的书籍,和查阅了相关的资料,就认为那样的是可行的。那篇文章实现的大概思路是用setNx命令和setEx配合使用。 setNx是一个耗时操作,因为它需要查询这个键是否存在,就算redis的百万的qps,在高并发的场景下,这种操作也是有问题的。关于redis实现分布式锁,redis官方推荐使用redlock。
一、redlock简介
在不同进程需要互斥地访问共享资源时,分布式锁是一种非常有用的技术手段。实现高效的分布式锁有三个属性需要考虑:
- 安全属性:互斥,不管什么时候,只有一个客户端持有锁
- 效率属性A:不会死锁
- 效率属性B:容错,只要大多数redis节点能够正常工作,客户端端都能获取和释放锁。
Redlock是redis官方提出的实现分布式锁管理器的算法。这个算法会比一般的普通方法更加安全可靠。关于这个算法的讨论可以看下官方文档。
二、怎么用java使用 redlock
在pom文件引入redis和redisson依赖:
<!-- redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.3.2</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
AquiredLockWorker接口类,,主要是用于获取锁后需要处理的逻辑:
/**
* Created by fangzhipeng on 2017/4/5.
* 获取锁后需要处理的逻辑
*/
public interface AquiredLockWorker<T> {
T invokeAfterLockAquire() throws Exception;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
DistributedLocker 获取锁管理类:
/**
* Created by fangzhipeng on 2017/4/5.
* 获取锁管理类
*/
public interface DistributedLocker {
/**
* 获取锁
* @param resourceName 锁的名称
* @param worker 获取锁后的处理类
* @param <T>
* @return 处理完具体的业务逻辑要返回的数据
* @throws UnableToAquireLockException
* @throws Exception
*/
<T> T lock(String resourceName, AquiredLockWorker<T> worker) throws UnableToAquireLockException, Exception;
<T> T lock(String resourceName, AquiredLockWorker<T> worker, int lockTime) throws UnableToAquireLockException, Exception;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
UnableToAquireLockException ,不能获取锁的异常类:
/**
* Created by fangzhipeng on 2017/4/5.
* 异常类
*/
public class UnableToAquireLockException extends RuntimeException {
public UnableToAquireLockException() {
}
public UnableToAquireLockException(String message) {
super(message);
}
public UnableToAquireLockException(String message, Throwable cause) {
super(message, cause);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
RedissonConnector 连接类:
/**
* Created by fangzhipeng on 2017/4/5.
* 获取RedissonClient连接类
*/
@Component
public class RedissonConnector {
RedissonClient redisson;
@PostConstruct
public void init(){
redisson = Redisson.create();
}
public RedissonClient getClient(){
return redisson;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
RedisLocker 类,实现了DistributedLocker:
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Created by fangzhipeng on 2017/4/5.
*/
@Component
public class RedisLocker implements DistributedLocker{
private final static String LOCKER_PREFIX = "lock:";
@Autowired
RedissonConnector redissonConnector;
@Override
public <T> T lock(String resourceName, AquiredLockWorker<T> worker) throws InterruptedException, UnableToAquireLockException, Exception {
return lock(resourceName, worker, 100);
}
@Override
public <T> T lock(String resourceName, AquiredLockWorker<T> worker, int lockTime) throws UnableToAquireLockException, Exception {
RedissonClient redisson= redissonConnector.getClient();
RLock lock = redisson.getLock(LOCKER_PREFIX + resourceName);
// Wait for 100 seconds seconds and automatically unlock it after lockTime seconds
boolean success = lock.tryLock(100, lockTime, TimeUnit.SECONDS);
if (success) {
try {
return worker.invokeAfterLockAquire();
} finally {
lock.unlock();
}
}
throw new UnableToAquireLockException();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
测试类:
@Autowired
RedisLocker distributedLocker;
@RequestMapping(value = "/redlock")
public String testRedlock() throws Exception{
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(5);
for (int i = 0; i < 5; ++i) { // create and start threads
new Thread(new Worker(startSignal, doneSignal)).start();
}
startSignal.countDown(); // let all threads proceed
doneSignal.await();
System.out.println("All processors done. Shutdown connection");
return "redlock";
}
class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run() {
try {
startSignal.await();
distributedLocker.lock("test",new AquiredLockWorker<Object>() {
@Override
public Object invokeAfterLockAquire() {
doTask();
return null;
}
});
}catch (Exception e){
}
}
void doTask() {
System.out.println(Thread.currentThread().getName() + " start");
Random random = new Random();
int _int = random.nextInt(200);
System.out.println(Thread.currentThread().getName() + " sleep " + _int + "millis");
try {
Thread.sleep(_int);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end");
doneSignal.countDown();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
运行测试类:
Thread-48 start
Thread-48 sleep 99millis
Thread-48 end
Thread-49 start
Thread-49 sleep 118millis
Thread-49 end
Thread-52 start
Thread-52 sleep 141millis
Thread-52 end
Thread-50 start
Thread-50 sleep 28millis
Thread-50 end
Thread-51 start
Thread-51 sleep 145millis
Thread-51 end
从运行结果上看,在异步任务的情况下,确实是获取锁之后才能运行线程。不管怎么样,这是redis官方推荐的一种方案,可靠性比较高。有什么问题欢迎留言。
三、参考资料
https://github.com/redisson/redisson
A Look at the Java Distributed In-Memory Data Model (Powered by Redis)
分布式锁之三:Redlock实现分布式锁的更多相关文章
- Redis 当成数据库在使用和可靠的分布式锁,Redlock 真的可行么?
怎样做可靠的分布式锁,Redlock 真的可行么? https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html ...
- 如何用Redlock实现分布式锁
转载请标明出处: http://blog.csdn.net/forezp/article/details/70305336 本文出自方志朋的博客 之前写过一篇文章<如何在springcloud分 ...
- 在.Net中使用RedLock实现分布式锁
⒈简介 RedLock 分布式锁算法由 Redis 的作者提出,大部分语言都有对应的实现,查看,RedLock.net 是 RedLock 分布式锁算法的 .NET 版实现,用来解决分布式下的并发问题 ...
- 基于Redis的分布式锁和Redlock算法
1 前言 前面写了4篇Redis底层实现和工程架构相关文章,感兴趣的读者可以回顾一下: Redis面试热点之底层实现篇-1 Redis面试热点之底层实现篇-2 Redis面试热点之工程架构篇-1 Re ...
- 如何做可靠的分布式锁,Redlock真的可行么
本文是对 Martin Kleppmann 的文章 How to do distributed locking 部分内容的翻译和总结,上次写 Redlock 的原因就是看到了 Martin 的这篇文章 ...
- Redis分布式锁升级版RedLock及SpringBoot实现
分布式锁概览 在多线程的环境下,为了保证一个代码块在同一时间只能由一个线程访问,Java中我们一般可以使用synchronized语法和ReetrantLock去保证,这实际上是本地锁的方式.但是现在 ...
- 身为一枚优秀的程序员必备的基于Redis的分布式锁和Redlock算法
1 前言 今天开始来和大家一起学习一下Redis实际应用篇,会写几个Redis的常见应用. 在我看来Redis最为典型的应用就是作为分布式缓存系统,其他的一些应用本质上并不是杀手锏功能,是基于Redi ...
- [Re:从零开始的分布式] 0.x——Reids实现分布式锁
上节提到了,分布式锁通常应满足如下要求,互斥性.高可用.高效率.可重入.锁失效这五个基本原则.由于Redis自身“快”的特点,所以高效率可以看作满足. 下文在单机情况下与多机情况下,对利用Redis实 ...
- 【分布式锁】07-Zookeeper实现分布式锁:Semaphore、读写锁实现原理
前言 前面已经讲解了Zookeeper可重入锁的实现原理,自己对分布式锁也有了更深的认知. 我在公众号中发了一个疑问,相比于Redis来说,Zookeeper的实现方式要更好一些,即便Redis作者实 ...
随机推荐
- iOS自动化探索(三)WebDriverAgent Python Client
之前我们在终端试着调用过WDA API, 今天我们在看一个Python封装的api库 https://github.com/openatx/facebook-wda 安装方式(一): pip inst ...
- 012——VUE中todos示例讲解class中应用表达式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 配置 Web 组件服务器 IIS 证书
用 IIS 6 配置 Web 组件证书(对于 Windows Server 2003) 使用 IIS 管理器向 Web 组件服务器分配证书.对合并池配置中的 Standard Edition ...
- Python基础学习(第6天)
1.zip函数 1)zip函数在只有一个参数时运作的方式. x = [1, 2, 3] x = zip(x) print x输出:[(1,), (2,), (3,)] 2)zip函数在没有参数时运作的 ...
- 剑指offer--30.二叉搜索树的后序遍历序列
正常情况下,因为二叉搜索树,左子树所有结点比根小,右子树所有结点比根大,所以循环一遍就能结束 ----------------------------------------------------- ...
- PostgreSQL.conf文件配置详解[转]
一.连接配置与安全认证 1.连接Connection Settings listen_addresses (string) 这个参数只有在启动数据库时,才能被设置.它指定数据库用来监听客户端连接的 ...
- 混用Application.LoadLevel 和 PhotonNetwork.LoadLevel
最近这一周从上周五晚上加完班回家夜里都12点了. 又赶紧送孩子去儿童医院 .. 就肺炎住院了. 真是有啥别有病呢. 悲剧的是我周三夜里陪了一夜后. 转天晚上也发烧了.. 周四 周五输了两天液. ...
- struct 字节对齐详解
一.什么是字节对齐,为什么要对齐? 现代计算机中内存空间都是按照byte划分的,从理论上讲似乎对任何类型的变量的访问可以从任何地址开始,但实际情况是在访问特定类型变量的时候经常在特 定的内存地址访问, ...
- HDU - 6231:K-th Number (不错的二分)
Alice are given an array A[1..N]A[1..N] with NN numbers. Now Alice want to build an array BB by a pa ...
- IntelliJ IDEA 安装破解详解
https://github.com/tengj/IntelliJ-IDEA-Tutorial IntelliJ IDEA官方中文文档 https://blog.csdn.net/newabcc/ar ...