5种基础数据结构

  1. Redis5种基础数据结构,分别是:string(字符串)、list(列表)、hash(字典)、set(集合)和zset(有序集合)。
  2. Redis所有数据结构都以唯一的key作为名称,然后通过这个唯一的key值来获取响应value数据,不同类型的数据结构的差异就在于value的结构不同。

string(字符串)

字符串是redis最简单的数据结构,内部就是一个字符数组。Redis字符串是动态的可变的,采用冗余分配空间的方式来减少内存的频繁分配。一般来说一个key的分配实际空间要高于字符串的实际长度len。

当字符长度小于1MB时,扩容都是加倍现有空间,如果长度超过1MB,扩容一次只会多扩1MB的空间,同时字符串最大长度为512MB

  • 键值对
[root@centos-linux redis]# ./bin/redis-cli
127.0.0.1:6379> set name codehole   # 增加
OK
127.0.0.1:6379> get name    # 获取key的值
"codehole"
127.0.0.1:6379> exists name   # 判断是否存在
(integer) 1
127.0.0.1:6379> set name1 codehole
OK
127.0.0.1:6379> set name2 hello
OK
127.0.0.1:6379> mget name1 name2 name3   # 批量获取,返回一个列表
1) "codehole"
2) "hello"
3) (nil)

127.0.0.1:6379> mset name1 lilei name2 zhangsan  name3 rick  # 批量set

127.0.0.1:6379> get name1
"lilei"
127.0.0.1:6379> expire name1 5  # 设置过期时间,单位为秒
(integer) 1
127.0.0.1:6379> get name1  # 等待5秒后get为空
(nil)

127.0.0.1:6379> setex name5 5 eric   # set时直接指定过期时间
OK
127.0.0.1:6379> get name5
"eric"
127.0.0.1:6379> get name5
(nil)
127.0.0.1:6379> setnx name7 lilei  # 如果name7不存在就执行set创建,如果存在则创建不成功
(integer) 1
127.0.0.1:6379> setnx name7 lilei
(integer) 0
127.0.0.1:6379> set age 20   # 如果value是数字,则可以使用incr进行自增
OK
127.0.0.1:6379> incr age
(integer) 21

字符串总结

  • Redis存入其实就是将数据结构使用Json序列化成字符串,取出信息则会经过一次反序列化过程
  • Redis数据均通过键值对方式保存,支持增set删del改set查get操作。
  • 可以对多个字符串进行批量读mget写mset,节省网络耗时开销
  • 可以通过expire或者setex进行key的过期设置
  • setnx指令如果key不存在就执行set创建,如果存在则创建不成功

列表

列表(list)类型是用来存储多个字符串,元素从左到右组成一个有序的集合.列表中的每个字符串被称为元素(element)。列表中每个元素都使用双向指针顺序,串起来可以同时支持前向和后向遍历。

列表常用来做异步队列使用,如队列和栈

先进先出的队列lpop

127.0.0.1:6379> rpush books python java golang
(integer) 3
127.0.0.1:6379> lpop books
"python"
127.0.0.1:6379> lpop books
"java"
127.0.0.1:6379> lpop books
"golang"
127.0.0.1:6379> lpop books
(nil)

先进后出的栈

127.0.0.1:6379> rpush books python java golang
(integer) 3
127.0.0.1:6379> rpop books
"golang"
127.0.0.1:6379> rpop books
"java"
127.0.0.1:6379> rpop books
"python"
127.0.0.1:6379> rpop books
(nil)