redis+lua現実ゲームでよく使われる機能
3145 ワード
, redis , 。 redis lua, , , , , , , :
class MyStorage extends Redis
{
public function safeDecr($key, $num)
{
$script = "local old=redis.call('get', KEYS[1]);
";
$script.= "if not old or old+0 < ARGV[1]+0 then return false;end;";
$script.= "return redis.call('decrBy', KEYS[1], ARGV[1]);
";
return $this->eval($script, array($key, $num), 1);
}
public function safeHDecr($key, $member, $num)
{
$script = "local old=redis.call('hGet', KEYS[1], ARGV[1]);
";
$script.= "if not old or old+0 < ARGV[2]+0 then return false;end;";
$script.= "redis.call('hIncrBy', KEYS[1], ARGV[1], -ARGV[2]);
";
$script.= "return true;";
return $this->eval($script, array($key, "", $member, $num), 2);
}
public function lock($key, $now, $expire)
{
$script = "local old=redis.call('get', KEYS[1]);
";
$script.= "if old and ARGV[1]+0 < old+0 then return false;end;
";
$script.= "redis.call('set', KEYS[1], ARGV[2]);
";
$script.= "return true;";
return $this->eval($script, array($key, "", $now, $expire), 2);
}
public function hlock($key, $member, $now, $expire)
{
$script = "local old=redis.call('hGet', KEYS[1], ARGV[1]);
";
$script.= "if old and ARGV[2]+0 < old+0 then return false;end;
";
$script.= "redis.call('hSet', KEYS[1], ARGV[1], ARGV[3]);
";
$script.= "return true;";
return $this->eval($script, array($key, "", "", $member, $now, $expire), 3);
}
public function rankSwap($key, $r1, $r2)
{
$script = "local r1score=redis.call('zScore', KEYS[1], ARGV[1]);
";
$script.= "local r2score=redis.call('zScore', KEYS[1], ARGV[2]);
";
$script.= "redis.call('zAdd', KEYS[1], r2score, ARGV[1]);
";
$script.= "return redis.call('zAdd', KEYS[1], r1score, ARGV[2]);
";
return $this->eval($script, array($key, "", $r1, $r2), 2);
}
}
$redis = new MyStorage();
// 1: key decr , ( )
$redis->safeDecr('mygold', 10);// mygold 10, false
// 2: hashtable Key decr , ( 、 )
$redis->safeHDecr('mygold2', 'gold', 10);
// 3: key,
$now = time();
$redis->lock('mylock', $now, $now + 5);//5 , , false
// 4: hashtable key, ( lock, , keys )
$now = time();
$redis->hlock('mylock', 'lock', $now, $now + 5);
// 5: ( , zadd , bug , , +N )
$redis->rankSwap('myrank', 'r1', 'r2');