有没有办法在 redis 中做到这一点?
SET counter 0
INCR counter
SET KEY:{counter} "Content of line 1"
INCR counter
SET KEY:{counter} "Different content of line 2"
我的示例代码应该替换(即,在运行时由 redis-cli 转换)为:
SET counter 0
INCR counter
SET KEY:1 "Content of line 1"
INCR counter
SET KEY:2 "Different content of line 2"
etc.
我的问题不是如何自动增加计数器。
我的问题是语法:How to include a generic {wildcard} into something like:
SET keyname:{currentcounter} "value" ...
感谢任何帮助。非常感谢!
伯尼
最佳答案
如果您使用的是 redis 2.6+,那么您可以使用 lua 脚本和 EVAL 命令,如下所示:
eval "local c = redis.call('incr', KEYS[1]);
return redis.call('set', KEYS[2] .. ':' .. c, ARGV[1])"
2 counter KEY "Content of line 1"
我将其分成多行以使其更易于阅读。
编辑
抱歉,我出差几天了。这是一个显示它有效的示例。
redis 127.0.0.1:6379> flushdb
OK
redis 127.0.0.1:6379> eval "local c = redis.call('incr', KEYS[1]); return redis.call('set', KEYS[2] .. ':' .. c, ARGV[1])" 2 counter KEY "Content of line 1"
OK
redis 127.0.0.1:6379> keys *
1) "KEY:1"
2) "counter"
redis 127.0.0.1:6379> get counter
"1"
redis 127.0.0.1:6379> get KEY:1
"Content of line 1"
redis 127.0.0.1:6379> eval "local c = redis.call('incr', KEYS[1]); return redis.call('set', KEYS[2] .. ':' .. c, ARGV[1])" 2 counter KEY "Content of the next thing"
OK
redis 127.0.0.1:6379> keys *
1) "KEY:1"
2) "KEY:2"
3) "counter"
redis 127.0.0.1:6379> get counter
"2"
redis 127.0.0.1:6379> get KEY:2
"Content of the next thing"
关于redis - 如何在 Redis key 中使用计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412894/