CommandReader

在命令上运行 RedisGears 函数。

CommandReader 允许您在命令上运行 RedisGears 函数,当您

  1. CommandReader 传递给 Java 代码中的 GearsBuilder.CreateGearsBuilder() 函数。

  2. 调用 register() 函数。

  3. 运行 RG.JEXECUTE 以注册您的代码。

  4. 使用 RG.TRIGGER 在命令上运行您的代码

    RG.TRIGGER <Trigger name> [arg1 arg2 ...]
    

参数

名称 类型 描述
trigger string 触发已注册的 RedisGears 函数运行的命令名称

输出记录

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

示例

以下示例演示了如何创建自定义命令以更新商品的库存。 它还添加了一个时间戳来跟踪上次补货发生的时间。

将哈希添加到数据库以表示库存项目

redis> HSET inventory:headphones:1 color "blue" stock 5 price 30.00
(integer) 3

示例代码

// Create the reader that will pass data to the pipe
CommandReader reader = new CommandReader();
// Set the name of the custom command
reader.setTrigger("Restock");
        
// Create the data pipe builder
GearsBuilder.CreateGearsBuilder(reader).map(r-> {
    // Parse the command arguments to get the key name and new stock value
    String itemKey = new String((byte[]) r[1], StandardCharsets.UTF_8);
    String newStock = new String((byte[]) r[2], StandardCharsets.UTF_8);
        	
    // Update the item's stock and add a timestamp
    GearsBuilder.execute("HSET", itemKey , "stock", newStock,
        			"last_restocked", Long.toString(System.currentTimeMillis()));
        	
    return "OK restocked " + itemKey;
}).register();

使用 RG.JEXECUTE 命令注册先前的代码后,运行 RG.TRIGGER 进行测试

redis> RG.TRIGGER Restock inventory:headphones:1 20
1) "OK restocked inventory:headphones:1"

该项目现在具有 stock 的更新值和一个 last_restocked 时间戳

redis> HGETALL inventory:headphones:1
1) "color"
2) "blue"
3) "stock"
4) "20"
5) "price"
6) "30.00"
7) "last_restocked"
8) "1643232394078"
为此页面评分
返回顶部 ↑