这篇文章主要介绍了redis使用Lua脚本解决多线程下的超卖问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一.多线程下引起的超卖问题呈现
1.1.我先初始化库存数量为1、订单数量为0
1.2.开启3个线程去执行业务
业务为:判断如果说库存数量大于0,则库存减1,订单数量加1
结果为:库存为-2,订单数量为3
原因:如下图所示,这是因为分别有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.修改后的代码如下
结果为:如下图所示,库存为0、订单数量为1,并没有出现超卖的问题且有2个线程抢不到。
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多线程超卖内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:redis使用Lua脚本解决多线程下的超卖问题及原因解析


基础教程推荐
- Python安装第三方库的方法(pip/conda、easy_install、setup.py) 2023-07-28
- SQL Server如何设置用户只能访问特定数据库和访问特定表或视图 2023-07-29
- Mariadb数据库主从复制同步配置过程实例 2023-07-25
- oracle数据库排序后如何获取第一条数据 2023-07-24
- Java程序员从笨鸟到菜鸟(五十三) 分布式之 Redis 2023-09-11
- Windows10系统中Oracle完全卸载正确步骤 2023-07-24
- oracle19c卸载教程的超详细教程 2023-07-23
- Python常见库matplotlib学习笔记之画图中各个模块的含义及修改方法 2023-07-27
- redis 数据库 2023-09-13
- redis乐观锁与悲观锁的实战 2023-07-13