一.多线程下引起的超卖问题呈现
1.1.我先初始化库存数量为1、订单数量为0
1.2.开启3个线程去执行业务
业务为:判断如果说库存数量大于0,则库存减1,订单数量加1
结果为:库存为-2,订单数量为3
原因:如下图所示,这是因为分别有6个指令(3个库存减1指令,3个订单数量加1指令)在redis服务端执行导致的。
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
|
namespace MengLin.Shopping.Redis.LuaScript { public class SecKillOriginal { static SecKillOriginal() { using (RedisClient client = new RedisClient( "127.0.0.1" , 6379 )) { //删除当前数据库中的所有Key, 默认删除的是db0 client.FlushDb(); //删除所有数据库中的key client.FlushAll(); //初始化库存数量为1和订单数量为0 client.Set( "inventoryNum" , 1 ); client.Set( "orderNum" , 0 ); } } public static void Show() { for ( int i = 0 ; i < 3 ; i++) { Task.Run(() => { using (RedisClient client = new RedisClient( "127.0.0.1" , 6379 )) { int inventoryNum = client.Get< int >( "inventoryNum" ); //如果库存数量大于0 if (inventoryNum > 0 ) { //给库存数量-1 var inventoryNum2 = client.Decr( "inventoryNum" ); Console.WriteLine($ "给库存数量-1后的数量-inventoryNum: {inventoryNum2}" ); //给订单数量+1 var orderNum = client.Incr( "orderNum" ); Console.WriteLine($ "给订单数量+1后的数量-orderNum: {orderNum}" ); } else { Console.WriteLine($ "抢购失败: 原因是因为没有库存" ); } } }); } } } } |
二.使用Lua脚本解决多线程下超卖的问题以及为什么
2.1.修改后的代码如下
结果为:如下图所示,库存为0、订单数量为1,并没有出现超卖的问题且有2个线程抢不到。
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
|
namespace MengLin.Shopping.Redis.LuaScript { public class SecKillLua { /// <summary> /// 使用Lua脚本解决多线程下变卖的问题 /// </summary> static SecKillLua() { using (RedisClient client = new RedisClient( "127.0.0.1" , 6379 )) { //删除当前数据库中的所有Key, 默认删除的是db0 client.FlushDb(); //删除所有数据库中的key client.FlushAll(); //初始化库存数量为1和订单数量为0 client.Set( "inventoryNum" , 1 ); client.Set( "orderNum" , 0 ); } } public static void Show() { for ( int i = 0 ; i < 3 ; i++) { Task.Run(() => { using (RedisClient client = new RedisClient( "127.0.0.1" , 6379 )) { //如果库存数量大于0,则给库存数量-1,给订单数量+1 var lua = @"local count = redis.call( 'get' ,KEYS[ 1 ]) if (tonumber(count)> 0 ) then -- return count redis.call( 'INCR' ,ARGV[ 1 ]) return redis.call( 'DECR' ,KEYS[ 1 ]) else return - 99 end"; Console.WriteLine(client.ExecLuaAsString(lua, keys: new [] { "inventoryNum" }, args: new [] { "orderNum" })); } }); } } } } |
三.为什么使用Lua脚本就能解决多线程下的超卖问题呢?
是因为Lua脚本把3个指令,分别是:判断库存数量是否大于0、库存减1、订单数量加1,这3个指令打包放在一起执行了且不能分割,相当于组装成了原子指令,所以避免了超卖问题。
在redis中我们尽量使用原子指令从而避免一些并发的问题。
到此这篇关于redis使用Lua脚本解决多线程下的超卖问题以及为什么的文章就介绍到这了,更多相关redis多线程超卖内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/menglin2010/p/17378027.html