服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Redis - 基于Redis实现分布式锁的方法(lua脚本版)

基于Redis实现分布式锁的方法(lua脚本版)

2021-08-03 16:41总有人想害朕 Redis

这篇文章主要介绍了基于Redis实现分布式锁的方法(lua脚本版),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1、前言

 

在java中,我们通过锁来避免由于竞争而造成的数据不一致问题。通常我们使用synchronized 、lock来实现。但是java中的锁只能保证在同一个jvm进程内中可用,在跨jvm进程,例如分布式系统上则不可靠了。

2、分布式锁

 

分布式锁,是一种思想,它的实现方式有很多,如基于数据库实现、基于缓存(redis等)实现、基于zookeeper实现等等。为了确保分布式锁可用,我们至少要确保锁的实现同时满足以下四个条件

  • 互斥性:在任意时刻,只有一个客户端能持有锁。
  • 不会发生死锁:即使客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
  • 具有容错性:只要大部分的redis节点正常运行,客户端就可以加锁和解锁。
  • 解铃还须系铃人:加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。

 3、基于redis实现分布式锁

 

以下代码实现了基于redis中间件的分布式锁。加锁的过程中为了保障setnx(设置key)和expire(设置超时时间)尽可能在一个事务中,使用到了lua脚本的方式,将需要完成的指令一并提交到redis中;

3.1、redisconfig.java

?
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
package com.demo.configuration;
 
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.serializer.genericjackson2jsonredisserializer;
import org.springframework.data.redis.serializer.stringredisserializer;
 
@configuration
public class redisconfig {
 
    @bean
    public redistemplate<string, object> redistemplate(redisconnectionfactory factory) {
        redistemplate<string, object> template = new redistemplate<>();
        template.setconnectionfactory(factory);
        // key采用string的序列化方式
        template.setkeyserializer(new stringredisserializer());
        // value序列化方式采用jackson
        template.setvalueserializer(new genericjackson2jsonredisserializer());
        template.afterpropertiesset();
        return template;
    }
 
}

3.2、redislockcontroller.java

?
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
package com.demo.controller;
 
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.core.io.classpathresource;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.core.script.defaultredisscript;
import org.springframework.scripting.support.resourcescriptsource;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
 
import java.util.arrays;
 
@restcontroller
@requestmapping("/redis")
public class redislockcontroller {
 
    @autowired
    private redistemplate<string, object> redistemplate;
 
    @requestmapping(value = "/lock/{key}/{uid}/{expire}")
    public long lock(@pathvariable("key") string key, @pathvariable("uid") string uid, @pathvariable("expire") integer expire) {
        long result = null;
        try {
            //调用lua脚本并执行
            defaultredisscript<long> redisscript = new defaultredisscript<>();
            redisscript.setresulttype(long.class);//返回类型是long
            //lua文件存放在resources目录下的redis文件夹内
            redisscript.setscriptsource(new resourcescriptsource(new classpathresource("redis/redis_lock.lua")));
            result = redistemplate.execute(redisscript, arrays.aslist(key), uid, expire);
            system.out.println("lock==" + result);
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }
 
    @requestmapping(value = "/unlock/{key}/{uid}")
    public long unlock(@pathvariable("key") string key, @pathvariable("uid") string uid) {
        long result = null;
        try {
            //调用lua脚本并执行
            defaultredisscript<long> redisscript = new defaultredisscript<>();
            redisscript.setresulttype(long.class);//返回类型是long
            //lua文件存放在resources目录下的redis文件夹内
            redisscript.setscriptsource(new resourcescriptsource(new classpathresource("redis/redis_unlock.lua")));
            result = redistemplate.execute(redisscript, arrays.aslist(key), uid);
            system.out.println("unlock==" + result);
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }
 
}

3.3、redis_lock.lua

?
1
2
3
4
5
if redis.call('setnx',keys[1],argv[1]) == 1 then
    return redis.call('expire',keys[1],argv[2])
else
    return 0
end

3.4、redis_unlock.lua

?
1
2
3
4
5
6
7
8
9
if redis.call("exists",keys[1]) == 0 then
    return 1
end
 
if redis.call('get',keys[1]) == argv[1] then
    return redis.call('del',keys[1])
else
    return 0
end

4、测试效果

 

key123为key,thread12345为value标识锁的主人,300为该锁的超时时间

加锁:锁主人为thread12345
http://127.0.0.1:8080/redis/lock/key123/thread12345/300

解锁:解锁人为thread123456
http://127.0.0.1:8080/redis/unlock/key123/thread123456

解锁:解锁人为thread12345
http://127.0.0.1:8080/redis/unlock/key123/thread12345

4.1、加锁,其他人解锁

基于Redis实现分布式锁的方法(lua脚本版)
基于Redis实现分布式锁的方法(lua脚本版)

thread12345加的锁,thread123456是解不了的,只有等thread12345自己解锁或者锁的超时时间过期

4.2、加锁,自己解锁

基于Redis实现分布式锁的方法(lua脚本版)
基于Redis实现分布式锁的方法(lua脚本版)

基于Redis实现分布式锁的方法(lua脚本版)

thread12345加的锁,thread12345自己随时可以解锁,也可以等锁的超时时间过期

5、总结

 

  •  使用redis锁,会有业务未执行完,锁过期的问题,也就是锁不具有可重入性的特点。
  • 使用redis锁,在尝试获取锁的时候,是非阻塞的,不满足在一定期限内不断尝试获取锁的场景。
  • 以上两点,都可以采用redisson锁解决。

到此这篇关于基于redis实现分布式锁的方法(lua脚本版)的文章就介绍到这了,更多相关redis实现分布式锁内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/WU4566285/article/details/116622270

延伸 · 阅读

精彩推荐
  • RedisRedis的配置、启动、操作和关闭方法

    Redis的配置、启动、操作和关闭方法

    今天小编就为大家分享一篇Redis的配置、启动、操作和关闭方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    大道化简5312019-11-14
  • Redisredis中如何使用lua脚本让你的灵活性提高5个逼格详解

    redis中如何使用lua脚本让你的灵活性提高5个逼格详解

    这篇文章主要给大家介绍了关于redis中如何使用lua脚本让你的灵活性提高5个逼格的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具...

    一线码农5812019-11-18
  • RedisRedis 事务知识点相关总结

    Redis 事务知识点相关总结

    这篇文章主要介绍了Redis 事务相关总结,帮助大家更好的理解和学习使用Redis,感兴趣的朋友可以了解下...

    AsiaYe8232021-07-28
  • Redisredis 交集、并集、差集的具体使用

    redis 交集、并集、差集的具体使用

    这篇文章主要介绍了redis 交集、并集、差集的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    xiaojin21cen10152021-07-27
  • Redis详解Redis复制原理

    详解Redis复制原理

    与大多数db一样,Redis也提供了复制机制,以满足故障恢复和负载均衡等需求。复制也是Redis高可用的基础,哨兵和集群都是建立在复制基础上实现高可用的...

    李留广10222021-08-09
  • Redisredis实现排行榜功能

    redis实现排行榜功能

    排行榜在很多地方都能使用到,redis的zset可以很方便地用来实现排行榜功能,本文就来简单的介绍一下如何使用,具有一定的参考价值,感兴趣的小伙伴们...

    乘月归5022021-08-05
  • RedisRedis如何实现数据库读写分离详解

    Redis如何实现数据库读写分离详解

    Redis的主从架构,能帮助我们实现读多,写少的情况,下面这篇文章主要给大家介绍了关于Redis如何实现数据库读写分离的相关资料,文中通过示例代码介绍...

    罗兵漂流记6092019-11-11
  • RedisRedis全量复制与部分复制示例详解

    Redis全量复制与部分复制示例详解

    这篇文章主要给大家介绍了关于Redis全量复制与部分复制的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Redis爬虫具有一定的参考学习...

    豆子先生5052019-11-27