Redis-key的设计技巧
- 把表名转换为key前缀, 比如: tag:
- 第二段放置用于区分key的字段--对应mysql中的主键的列名
- 第三段放置主键值
- 第三段写列名
用户表user, 转换为redis的key-value存储
userid | username | password | |
9 | Lisi | 111111 | lisi@163.com |
比如:
127.0.0.1:6379> set user:userid:9:username lisi
OK
127.0.0.1:6379> set user:userid:9:password 111111
OK
127.0.0.1:6379> set user:userid:9:email lisi@163.com
OK
127.0.0.1:6379>
127.0.0.1:6379> keys user:userid:9* #查找有几个属性
1) "user:userid:9:password"
2) "user:userid:9:username"
3) "user:userid:9:email"
127.0.0.1:6379>
注意: 实际中经常要通过username来查找信息, 只能通过再建立一个对应关系
127.0.0.1:6379> set user:username:lisi:userid 9 #建立一个username和userid对应的表
OK
127.0.0.1:6379>
127.0.0.1:6379> get user:username:lisi:userid #获取到userid
"9"
127.0.0.1:6379>
127.0.0.1:6379> keys user:userid:9* #通过userid找到所有键
1) "user:userid:9:password"
2) "user:userid:9:username"
3) "user:userid:9:email"
127.0.0.1:6379>
127.0.0.1:6379> get user:userid:9:email #获取其它键的信息
"lisi@163.com"
127.0.0.1:6379>
如果要通过email查询, 只能再维护
127.0.0.1:6379> set user:email:lisi@163.com:userid 9
OK
127.0.0.1:6379> get user:email:lisi@163.com:userid
"9"
127.0.0.1:6379> keys user:userid:9*
1) "user:userid:9:username"
2) "user:userid:9:email"
3) "user:userid:9:password"
127.0.0.1:6379>