用户函数

通过 TFCALLTFCALLASYNC 执行 JavaScript 函数

Redis 开源 Redis Enterprise 软件 Redis Cloud Redis 开源 用于 Kubernetes 的 Redis Enterprise 客户端

所有跟随函数名称的 TFCALL 命令参数都传递给函数回调。以下示例展示了如何实现一个简单的函数,该函数返回类型为字符串或哈希的键的值

#!js api_version=1.0 name=lib

redis.registerFunction('my_get', function(client, key_name){
    if (client.call('type', key_name) == 'string') {
        return client.call('get', key_name);
    }
    if (client.call('type', key_name) == 'hash') {
        return client.call('hgetall', key_name);
    }
    throw "Unsupported type";
});

运行上述函数的示例

127.0.0.1:6379> set x 1
OK
127.0.0.1:6379> TFCALL lib.my_get 1 x
"1"
127.0.0.1:6379> hset h a b x y
(integer) 2
127.0.0.1:6379> TFCALL lib.my_get 1 h
1) "a"
2) "b"
3) "x"
4) "y"

也可以将所有函数参数作为 JS 数组获取。 这是我们如何扩展上面的示例以接受多个键并返回它们的值

#!js api_version=1.0 name=lib

redis.registerFunction('my_get', function(client, ...keys){
    var results = [];
    keys.forEach((key_name)=> {
            if (client.call('type', key_name) == 'string') {
                results.push(client.call('get', key_name));
                return;
            }
            if (client.call('type', key_name) == 'hash') {
                results.push(client.call('hgetall', key_name));
                return;
            }
            results.push("Unsupported type");
        }
    );
    return results;

});

运行示例

127.0.0.1:6379> TFCALL foo.my_get 2 x h
1) "1"
2) 1) "a"
   2) "b"
   3) "x"
   4) "y"
评价此页
返回顶部 ↑