dynamonet/

redis

Redis 扩展包装器,具有良好的 Lua 脚本支持和其他有用工具

v1.3.2 2022-09-27 17:17 UTC

This package is auto-updated.

Last update: 2024-09-27 22:01:31 UTC


README

phpredis 扩展的包装器,具有良好的管道接口、Lua 脚本支持和其他有用工具。

安装

composer install dynamonet/redis

初始化

use Dynamo\Redis\Client as RedisClient;

$redis = new RedisClient([
    'host' => 'localhost',
    'port' => 6379,
    //'timeout' => xxx,
    //'retry_interval' => xxx, //
]);

// you can now start sending commands, without the need for an explicit "connect" call
$redis->set('mykey', 'value');

管道

$result = $redis->pipeline()
    ->set('key1', 'value1')
    ->incr('key2')
    ->get('key2')
    ->exec();

var_dump($result); // an array with the result for every queued command

Redis 7 函数

Redis 7 引入了“函数”的概念,这些函数是命名脚本,通常用 Lua 编写,您可以通过选择的名字调用它们

FCALL myHelloFunction 1 "John Snow"

在 Redis 函数之前,唯一调用自定义脚本的方法是使用由 LOAD SCRIPT 命令返回的 SHA1 字符串 🤮

此库已经支持 Redis 7 函数。您只需注册您的函数,然后就像调用客户端上的现有命令一样调用它们即可。

// Register my custom functions
$redis->loadFunctionScript($path_to_my_functions_script, [
    'functionA' => 1,
    'functionB' => 2,
    'functionC' => 0,
]);

注意传递给第二个参数的关联数组。此参数是必需的,也是我们唯一告知客户端脚本中公开了哪些函数以及每个自定义函数有多少个必需键(键)参数的方法。

// Invoking my functions
$redis->functionA('Hello');
$redis->functionB('World', 2);
$redis->functionA();

Lua 脚本

Redis 中的 Lua 脚本类似于传统的数据库存储过程,但更加强大,因为您可以用 Lua 编写它们,所以您可以使用条件、循环以及 Lua 语言中可用的所有流程控制结构。如果您使用的是低于 7 的任何版本,Redis 脚本(如果有的话)的缺点是必须使用 SHA1 字符串来调用您的脚本。幸运的是,此库将使您的 Lua 脚本变得更加愉快。

推荐使用:将 Lua 脚本保存在单独的 .lua 文件中,将它们加载到客户端,并为每个脚本分配一个别名

use Dynamo\Redis\LuaScript;

$redis->loadScript(
    LuaScript::fromFile(
        $path_to_my_lua_script,
        2, // amount of mandatory arguments
        'myluacmd' //alias for the script
    ),
    true //register the script NOW. If "false" is provided, it will be lazy-loaded
);

//now, you can call your Lua command as if it were a regular Redis command
$redis->myluacmd('blablabla', 2);

//you can also call your custom commands in a pipeline
$result = $redis->pipeline()
    ->set('key1', 'value1')
    ->incr('key2')
    ->get('key2')
    ->myluacmd('blablabla', 2)
    ->exec();