数据类型
String
字符串,一个 key 对应一个 value,可以保存序列化对象
127.0.0.1:6379> set name "zhangsan"
OK
127.0.0.1:6379> get name
"zhangsan"
Hash
键值对集合,用于存储多组key-value
- hmset 设置键值对
- hgetall 获取所以键值对
- hvals 获取所有值
- hkeys 获取所有键
- hlen 获取键值对个数
127.0.0.1:6379> hmset object name "zhangsan" age 24 high 182
OK
127.0.0.1:6379> hget object name
"zhangsan"
127.0.0.1:6379> hkeys object
1) "name"
2) "age"
3) "high"
127.0.0.1:6379> hvals object
1) "zhangsan"
2) "24"
3) "182"
127.0.0.1:6379> hgetall object
1) "name"
2) "zhangsan"
3) "age"
4) "24"
5) "high"
6) "182"
127.0.0.1:6379> hlen object
(integer) 3
List
字符串列表,顺序插入
- lpush 左边顺序插入字段
- rpush 右边顺序插入字段
127.0.0.1:6379> lpush mylist 1 2 3
(integer) 3
127.0.0.1:6379> rpush mylist 4 5 6
(integer) 6
127.0.0.1:6379> lrange mylist 0 6
1) "3"
2) "2"
3) "1"
4) "4"
5) "5"
6) "6"
127.0.0.1:6379>
Set
字符串无序集合,集合是通过哈希表实现的,保证唯一性,添加,删除,查找的复杂度都是 O(1)
127.0.0.1:6379> sadd myset zhangsan
(integer) 1
127.0.0.1:6379> sadd myset lisi
(integer) 1
127.0.0.1:6379> sadd myset zhangsan
(integer) 0
127.0.0.1:6379> sadd myset 1
(integer) 1
127.0.0.1:6379> smembers myset
1) "zhangsan"
2) "lisi"
3) "1"
127.0.0.1:6379>
Sorted Set
字符串有序集合,和Set区别是每个元素都会关联一个double类型的分数。通过此分数来为集合中的成员进行从小到大的排序
127.0.0.1:6379> zadd myzset 0 zhangsan
(integer) 1
127.0.0.1:6379> zadd myzset 3 lisi
(integer) 1
127.0.0.1:6379> zadd myzset 1 wanger
(integer) 1
127.0.0.1:6379> zadd myzset 2 zhangsan
(integer) 0
127.0.0.1:6379> ZRANGEBYSCORE myzset 0 1000
1) "wanger"
2) "zhangsan"
3) "lisi"
127.0.0.1:6379>
应用场景
操作
切换数据库
默认数据库0,默认数据库数量16,可设置数据库数量
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> select 15
OK
127.0.0.1:6379[15]> select 16
(error) ERR invalid DB index
127.0.0.1:6379[15]>
设置密码
默认无密码,可配置,可修改,设置后客户端连接需要密码
- CONFIG get requirepass 查看密码
- CONFIG set requirepass "8888" 设置密码
- AUTH 8888 输入密码
127.0.0.1:6379> CONFIG get requirepass
1) "requirepass"
2) ""
127.0.0.1:6379> CONFIG set requirepass "8888"
OK
127.0.0.1:6379> set name zhangsan
(error) NOAUTH Authentication required.
127.0.0.1:6379> AUTH 8888
OK
127.0.0.1:6379> set name zhangsan
OK
删除/查看所有
- keys * 查看所有
- flushall 清空当前数据库所有数据
- flushdb 清空所有数据数据
127.0.0.1:6379> keys *
1) "key"
2) "mylist"
3) "myzset"
4) "name"
5) "object"
6) "myset"
127.0.0.1:6379> flushall
OK
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379>