Redis Insight 快速入门
使用 Redis Insight 的触发器和函数入门
Redis 堆栈 | Redis 社区版 | Redis 企业软件 | Redis 云 | Redis 社区版 | 适用于 Kubernetes 的 Redis Enterprise | 客户 |
---|
确保您已安装并运行 Redis Stack。或者,您可以创建一个免费的 Redis Cloud 帐户。
如果您尚未安装 Redis Insight,可以在此处下载最新版本。如果这是您第一次使用 Redis Insight,您可能希望先通读 Redis Insight 指南,然后再继续阅读本指南。
连接到 Redis 堆栈
打开 Redis Insight 应用程序,然后单击其数据库别名连接到您的数据库。

加载库
单击触发器和函数图标,然后单击 + 库,如下所示。

将您的代码添加到右侧面板的 Library Code 部分,然后单击 Add Library (添加库)。

添加库后,您将看到以下内容:

这TFCALL
command 用于执行 JavaScript 函数。如果命令失败,将返回错误。单击左下角的 >_ CLI 按钮以打开控制台窗口,然后运行如下所示的命令。

要更新库,您可以通过单击编辑(铅笔)图标直接在界面中编辑库代码。保存更改时,将重新加载库。

上传外部文件
像以前一样单击 + 添加库 按钮,而不是将代码直接添加到编辑器中,而是单击 上传 按钮,从文件浏览器中选择文件,然后单击 添加库。该文件需要包含标头,其中包含引擎标识符、API 版本和库名称:#!js api_version=1.0 name=myFirstLibrary
.

创建触发器
Redis 中的函数可以使用键空间触发器响应事件。虽然这些事件中的大多数是由命令调用启动的,但它们也包括密钥过期或从数据库中删除时发生的事件。
有关支持事件的完整列表,请参阅 Redis 密钥空间通知页面。
以下代码创建一个新的键空间触发器,该触发器使用最新的更新时间将新字段添加到新的或更新的哈希中。
#!js name=myFirstLibrary api_version=1.0
function addLastUpdatedField(client, data) {
if(data.event == 'hset') {
var currentDateTime = Date.now();
client.call('hset', data.key, 'last_updated', currentDateTime.toString());
}
}
// Register the KeySpaceTrigger 'AddLastUpdated' for keys with the prefix 'fellowship'
// with the callback function 'addLastUpdatedField'.
redis.registerKeySpaceTrigger('addLastUpdated', 'fellowship:', addLastUpdatedField);"
Update the existing library as before and then, using the Redis Insight console, add a new hash with the required prefix to trigger the function.
> HSET fellowship:1 name "Frodo Baggins" title "The One Ring Bearer"
Run the HGETALL
command to check if the last updated time is added to the example.
> HGETALL fellowship:1
1) "name"
2) "Frodo Baggins"
3) "title"
4) "The One Ring Bearer"
5) "last_updated"
6) "1693238681822"
On this page