CommandReader
在命令上运行 RedisGears 函数。
当您执行以下操作时,CommandReader
允许您在命令上运行 RedisGears 函数:
-
将
CommandReader
传递给 Java 代码中的GearsBuilder.CreateGearsBuilder()
函数。 -
调用
register()
函数。 -
运行
RG.JEXECUTE
来注册您的代码。 -
使用
RG.TRIGGER
在命令上运行您的代码RG.TRIGGER <Trigger name> [arg1 arg2 ...]
参数
名称 | 类型 | 描述 |
---|---|---|
触发器 | 字符串 | 触发已注册 RedisGears 函数运行的命令名称 |
输出记录
输出包含命令触发器名称和参数的记录。
示例
以下示例展示了如何创建自定义命令来更新商品库存。它还会添加时间戳以跟踪上次补货时间。
在数据库中添加一个表示库存商品的哈希表
redis> HSET inventory🎧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🎧1 20
1) "OK restocked inventory🎧1"
该商品现在拥有 stock
的更新值和 last_restocked
时间戳
redis> HGETALL inventory🎧1
1) "color"
2) "blue"
3) "stock"
4) "20"
5) "price"
6) "30.00"
7) "last_restocked"
8) "1643232394078"