redis使用lua脚本保证原子性

redis使用lua脚本保证原子性

    Eval的使用 语法:
EVAL script numkeys key [key ...] arg [arg ...]

首先大家一定要知道eval的语法格式,其中:

  1. script: 你的lua脚本
  2. numkeys: key的个数
  3. key: redis中各种数据结构的替代符号
  4. arg: 你的自定义参数
    示例:
eval "return redis.call(mset,KEYS[1],ARGV[1],KEYS[2],ARGV[2])" 2 foo abc abc 234
eval "return redis.call(hset,KEYS[1],ARGV[1],ARGV[2])" 1 foo abc 123
    找到hash中age小于指定值的所有数据,lua脚本如下:
local result={
          
   };
local myperson=KEYS[1];
local nums=ARGV[1];

local myresult =redis.call("hkeys",myperson);

for i,v in ipairs(myresult) do
   local hval= redis.call("hget",myperson,v);
   redis.log(redis.LOG_WARNING,hval);
   if(tonumber(hval)<tonumber(nums)) then
      table.insert(result,1,v);
   end
end

return  result;
    php使用lua脚本
function getLock(){
          
   //生成锁脚本
    $script = <<<LUA
        local key = KEYS[1]
        local expire = ARGV[1]
        if redis.call(setnx,key,1)==1 then
            return redis.call(expire,key,expire)
        end
        return 0    
LUA;
    return Redis::eval($script,[key,500],1);
}
经验分享 程序员 微信小程序 职场和发展