1. MySQL 数据格式缓存到 Redis
MySQL 的 user 表:
id name job age
1 boss it 18
2 wei it 24
3 cokz it 30
Redis 的 hash 类型:key名规则:对应数据库的表名:ID
key field1 value field2 value field3 value
user:1 name boss job it age 18
user:2 name wei job it age 24
user:3 name cokz job it age 30
2. 哈希类型常用命令
命令 | 含义 | 语法 |
---|---|---|
HMSET | 设置一个hash key | HMSET key 字段1 value1 字段2 value2 |
HMGET | 查看 hash key | HMGETkey 字段1 value1 字段2 value2 |
HMGETALL | 查看key中的所有值 | HMGETALL key |
3. 创建哈希key
语法:HMSET key field value [field value ...]
127.0.0.1:6379> HMSET user:1 name boss job it age 18
OK
127.0.0.1:6379> HMSET user:2 name wei job it age 24
OK
127.0.0.1:6379> HMSET user:3 name cokz job it age 30
OK
4. 查看Hash里的指定字段的值
# MySQL:select name from user where id = 1;
127.0.0.1:6379> HMGET user:1 name
1) "boss"
127.0.0.1:6379> HMGET user:1 name age job age
1) "boss"
2) "18"
3) "it"
4) "18"
5. 查看Hash里的所有字段的值
# MySQL:select * from user where id = 1;
HGETALL user:1
127.0.0.1:6379> HGETALL user:1
1) "name"
2) "boss"
3) "job"
4) "it"
5) "age"
6) "18"
6. 向已有的key中增加字段
127.0.0.1:6379> HMSET user:1 job IT
OK
127.0.0.1:6379> HGETALL user:1
1) "name"
2) "boss"
3) "job"
4) "IT"
5) "age"
6) "18"