CommandOverrider 命令

覆盖 Redis 命令。

Redis 堆栈

CommandOverrider允许您覆盖和自定义 Redis 命令。

  1. CommandOverriderGearsBuilder.CreateGearsBuilder()函数。
  2. 调用register()功能。
  3. RG.JEXECUTE以注册您的代码。
注意:
如果您注册使用CommandOverriderreadervalue 为"CommandReader"当您运行RG.DUMPREGISTRATIONS命令,而不是"CommandOverrider".

参数

名字 类型 描述
命令 字符串 要覆盖的命令
前缀 字符串 仅覆盖以此字符串开头的键的命令

输出记录

输出包含命令名称和参数的记录。

以下示例显示如何覆盖HSET命令,以便它还会添加一个last_modified“user:” 哈希的时间戳。

将一些用户数据添加为哈希值:

redis> HSET user:1 name "morgan" posts 201
(integer) 2

Example code:

// Create the reader that will pass data to the pipe
CommandOverrider overrider = new CommandOverrider();
// Override the HSET command
overrider.setCommand("HSET");
// Only override HSET for keys that start with "user:"
overrider.setPrefix("user:");

// Create the data pipe builder
GearsBuilder.CreateGearsBuilder(overrider).map(r-> {
    // Get the operation arguments
    ArrayList<String> operationArguments = new ArrayList<String>();
    for (int i = 1; i < r.length; i++) {
        operationArguments.add(new String((byte[]) r[i], StandardCharsets.UTF_8));
    }

    // Add a last-modified field and a corresponding timestamp to the operation arguments
    operationArguments.add("last-modified");
    operationArguments.add(Long.toString(System.currentTimeMillis()));

    // Run the enriched HSET operation
    Object reply = GearsBuilder.callNext(operationArguments.toArray(new String[0]));
    
    return reply.toString();
}).register(ExecutionMode.SYNC);

After you register the previous code with the RG.JEXECUTE command, try to update the user's data with HSET to test it:

redis> HSET user:1 posts 234
"OK"

Now the user's profile should have the updated value for posts and a last_modified timestamp:

redis> HGETALL user:1
1) "name"
2) "morgan"
3) "posts"
4) "234"
5) "last_modified"
6) "1643237927663"