On-demand loading of scripts into redis. Added some more script options.

This commit is contained in:
Greyscale 2020-06-24 16:33:31 +02:00
parent 4570e758c1
commit 4bfecc524e
5 changed files with 76 additions and 3 deletions

View file

@ -10,8 +10,6 @@ abstract class LuaExtension {
public function __construct(\Redis $redis)
{
$this->redis = $redis;
$this->load();
}
public function getFunctionNames() : array {
@ -25,7 +23,7 @@ abstract class LuaExtension {
return $this->hash;
}
protected function load(){
public function load(){
if(!$this->hash){
$exists = $this->redis->script('exists', $this->getScript());
if(!$exists[0]){

View file

@ -0,0 +1,23 @@
<?php
namespace Benzine\Redis\Lua;
class SetIfLower extends LuaExtension
{
protected function getScript() : string
{
return <<<'LUA'
local c = tonumber(redis.call('get', KEYS[1]));
if c then
if tonumber(ARGV[1]) < c then
redis.call('set', KEYS[1], ARGV[1])
return tonumber(ARGV[1]) - c
else
return 0
end
else
return redis.call('set', KEYS[1], ARGV[1])
end
LUA;
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Benzine\Redis\Lua;
class ZAddIfHigher extends LuaExtension
{
protected function getScript() : string
{
return <<<'LUA'
local c = tonumber(redis.call('zscore', KEYS[1], ARGV[1]));
if c then
if tonumber(KEYS[2]) > c then
redis.call('zadd', KEYS[1], KEYS[2], ARGV[1])
return tonumber(KEYS[2]) - c
else
return 0
end
else
redis.call('zadd', KEYS[1], KEYS[2], ARGV[1])
return 'OK'
end
LUA;
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Benzine\Redis\Lua;
class ZAddIfLower extends LuaExtension
{
protected function getScript() : string
{
return <<<'LUA'
local c = tonumber(redis.call('zscore', KEYS[1], ARGV[1]));
if c then
if tonumber(KEYS[2]) < c then
redis.call('zadd', KEYS[1], KEYS[2], ARGV[1])
return tonumber(KEYS[2]) - c
else
return 0
end
else
redis.call('zadd', KEYS[1], KEYS[2], ARGV[1])
return 'OK'
end
LUA;
}
}

View file

@ -11,6 +11,9 @@ class Redis extends \Redis
public function initialiseExtensions() : void
{
$this->scripts[] = new Lua\SetIfHigher($this);
$this->scripts[] = new Lua\SetIfLower($this);
$this->scripts[] = new Lua\ZAddIfHigher($this);
$this->scripts[] = new Lua\ZAddIfLower($this);
}
public function connect($host, $port = 6379, $timeout = 0.0, $reserved = null, $retryInterval = 0, $readTimeout = 0.0)
@ -24,6 +27,7 @@ class Redis extends \Redis
foreach($this->scripts as $script){
foreach($script->getFunctionNames() as $functionName){
if(strtolower($name) == strtolower($functionName)){
$script->load();
return $this->evalSha($script->getHash(), $arguments);
}
}