lua脚本
控制语句
local x = 7
if x > 10 then
print("x is greater than 10")
elseif x > 5 then
print("x is greater than 5 but less than or equal to 10")
else
print("x is less than or equal to 5")
end
redis
redis支持的命令
EVAL的作用是执行lua脚本
EVAL script numkeys key [key ...] arg [arg ...]
script
:Lua 脚本代码,需要替换为真正的脚本。numkeys
:脚本中涉及的键的数量。key
:表示键的总数[key ...]
:脚本中使用的键的集合。arg [arg ...]
:传递给脚本的参数集合(不用告知redis有多少个arg)
EVAL "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1)
then
redis.call('expire', KEYS[1], ARGV[1]);
return 1;
else
return 0;
end;"
1 test_key
600 test_value
可直接复制该命令到redis中即可执行
1 test_key : 1表示key参数有1个;test_key表示参数集合
600 test_value:这两个值是参数,其中600表示600秒(expire的单位是秒)(警告:600前面不用再写一个2)
脚本含义:
检查是否存在test_key,test_value 的键值对,如果存在,则设置过期时间600秒,并返回1;如果不存在,则直接返回0
执行结果
使用场景
1.redission使用lua+hash实现加锁
redis-redission的加锁源码与看门狗机制_redission 看门狗-CSDN博客
2.秒杀活动:为了避免redis扣减库存后,mysql未扣减前宕机导致的redis丢失库存问题。在redis扣减库存时,使用list存储用户购买物品信息,作为后续的验证工作(list中存储购买时间,等1分钟后检查是否生成订单)。 利用lua同时做扣减库存、存储用户购买信息的操作