库配置
如何在 JavaScript 函数中使用配置
Redis 开源 | Redis Enterprise Software | Redis Cloud | Redis 开源 | Redis Enterprise for Kubernetes | 客户端 |
---|
编写库时,您可能希望提供加载配置,以便不同的用户可以使用相同的库,但行为略有不同,而无需更改基本代码。 例如,假设您编写一个库,该库将一个 __last_updated__
字段添加到哈希中(您可以看到如何使用键空间触发器来完成它),代码如下所示
#!js api_version=1.0 name=lib
redis.registerFunction("hset", function(client, key, field, val){
// get the current time in ms
var curr_time = client.call("time")[0];
return client.call('hset', key, field, val, "__last_update__", curr_time);
});
运行示例
127.0.0.1:6379> TFCALL lib.hset k a b 0
(integer) 2
127.0.0.1:6379> hgetall k
1) "foo"
2) "bar"
3) "__last_update__"
4) "1658653125"
上述代码的问题在于 __last_update__
字段是硬编码的。 如果我们想允许用户在运行时配置它怎么办? 触发器和函数提供用于在加载时使用传递给 TFUNCTION LOAD
命令的CONFIG
参数指定库配置。 配置参数接受 JSON 对象的字符串表示形式。 JSON 将作为 JS 对象在 redis.config
变量下提供给库。 我们可以更改上面的示例以接受 __last_update__
字段名称作为库配置。 代码如下所示
#!js api_version=1.0 name=lib
var last_update_field_name = "__last_update__"
if (redis.config.last_update_field_name !== undefined) {
if (typeof redis.config.last_update_field_name != 'string') {
throw "last_update_field_name must be a string";
}
last_update_field_name = redis.config.last_update_field_name
}
redis.registerFunction("hset", function(client, key, field, val){
// get the current time in ms
var curr_time = client.call("time")[0];
return client.call('hset', key, field, val, last_update_field_name, curr_time);
});
请注意,在上面的示例中,我们首先将 last_update_field_name
设置为 __last_update__
,这是配置未提供值时的默认值。 然后,我们检查我们的配置中是否有 last_update_field_name
,如果有,我们就使用它。 我们现在可以使用CONFIG
参数加载我们的函数
> redis-cli -x TFUNCTION LOAD REPLACE CONFIG '{"last_update_field_name":"last_update"}' < <path to code file>
OK
我们可以看到最后一个更新字段名称是 last_update
127.0.0.1:6379> TFCALL lib.hset h a b 0
(integer) 2
127.0.0.1:6379> hgetall h
1) "a"
2) "b"
3) "last_update"
4) "1658654047"
请注意,触发器和函数仅为库提供 JSON 配置。 **库有责任验证给定配置的正确性**。