redis - 如何在 Redis key 中使用计数器?

标签 redis

有没有办法在 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/

相关文章:

asp.net-mvc - 如何使用 RedisSessionStateProvider 配置 Redis 缓存过期?

azure - Azure redis 缓存补丁计划配置中的维护窗口属性是什么?

design-patterns - 里兹模式

ruby redis 客户端扫描无法使用 3.0.7 工作

node.js - Nodejs,在继续执行之前不等待 Redis 查询完成

redis - Ubuntu 的 Redis AOF 文件的默认位置是什么?

redis - 将 redis.conf 文件移至 AMI 时,Packer 给予我 SCP 权限被拒绝

caching - Redis 或 Hazelcast,或其他?

json - 如何确保我的 View 在数据库操作后呈现?

redis - 在redis中维护全局计数器的缺点