php中使用redis执行lua脚本

<?php

$lua = <<<LUA
    local sequenceKey = KEYS[1]
    local time        = KEYS[2]
    local result      = redis.call("setnx", sequenceKey, 1)
    if (result == 1)
    then
        redis.call("expire", sequenceKey, time) 
    end
    return result
LUA;

$redis = new \Redis();
$redis->connect('127.0.0.1');
$redis->auth('admin');
$redis->select(0);
$lock = $redis->eval($lua, ['lock', 60], 2);
$luaError = $redis->getLastError();
if (isset($luaError)) {
    printf("lua error" . $luaError);die;
}
if (!$lock) {
   printf("locking!!!");die;
}
printf("do something!!!");die;

  

posted @ 2021-09-26 19:23  大雾哥  阅读(695)  评论(0编辑  收藏  举报