一.多线程下引起的超卖问题呈现
1.1.我先初始化库存数量为1、订单数量为0
业务为:判断如果说库存数量大于0,则库存减1,订单数量加1
原因:如下图所示,这是因为分别有6个指令(3个库存减1指令,3个订单数量加1指令)在redis服务端执行导致的。
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.修改后的代码如下
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中我们尽量使用原子指令从而避免一些并发的问题。