用户功能

通过以下方式执行 JavaScript 函数TFCALLTFCALLASYNC

Redis 堆栈 Redis 社区版 Redis 企业软件 Redis 云 Redis 社区版 适用于 Kubernetes 的 Redis Enterprise 客户

TFCALL函数名称后面的命令参数将传递给函数回调。以下示例说明如何实现一个简单函数,该函数返回 string 或 hash 类型的键的值:

#!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";
});

Example of running the preceding function:

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"

It is also possible to get all the function arguments as a JS array. This is how we can extend the above example to accept multiple keys and return their values:

#!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;

});

Run example:

127.0.0.1:6379> TFCALL foo.my_get 2 x h
1) "1"
2) 1) "a"
   2) "b"
   3) "x"
   4) "y"
RATE THIS PAGE
Back to top ↑