Node.js – Redis 中的监控模式

Redis 还支持monitor 命令,让用户可以查看 Redis 服务器通过所有客户端连接接收到的所有命令。这些连接包括来自任何地方的命令,包括其他客户端库和计算机。

监控事件将监控所有这些都在Redis的服务器上执行的命令监控已启用。来自监视器的回调从Redis 服务器接收时间戳、命令数组以及原始监视字符串。

语法

client.monitor( function(callback) )

示例 1

创建一个名为“ monitor.js ”的文件并复制以下代码。创建文件后,使用命令“ node monitor.js ”运行此代码,如下例所示:

// 监控模式演示示例

// 导入redis模块
const redis = require("redis");

// 创建 redis 客户端
const client = redis.createClient();

// 说明我们正在进入监控模式
client.monitor(function(err, res) {
   console.log("进入监控模式。");
});

// 在redis中设置值
client.set("hello", "nhooo");

// 定义监视器输出
client.on("monitor", function(time, args, rawReply) {
   console.log(time + ": " + args); // 1458910076.446514:['set', 'foo', 'bar']
});
输出结果
进入监控模式。
1623087421.448855: set,hello,nhooo

示例 2

让我们再举一个例子 -

// 监控模式演示示例

// 导入redis模块
const redis = require("redis");

// 创建 redis 客户端
const client = redis.createClient();

// 说明我们正在进入监控模式
client.monitor(function(err, res) {
   console.log("进入监控模式。");
});

// 在redis中设置值
client.set("hello", "nhooo");
client.get("hello");
client.set("key", "value");
client.set("key2", "value2");
client.get("key2");

// 定义监视器输出
client.on("monitor", function(time, args, rawReply) {
   console.log(time + ": " + args); // 1458910076.446514:['set', 'foo', 'bar']
});
输出结果
进入监控模式。
1623088106.382888: set,hello,nhooo
1623088106.382902: get,hello
1623088106.382919: set,key,value
1623088106.383023: set,key2,value2
1623088106.383033: get,key2