Redis有哪些数据结构?
字符串String、字典Hash、列表List、集合Set、有序集合SortedSet。
很多人面试时都遇到过这种场景吧?
其实除了上面的几种常见数据结构,还需要加上 数据结构HyperLogLog、Geo。
可是很多人不知道redis 不仅有上面的几种数据结构,还内藏了内部的数据结构。即redis可以分为外部数据结构和内部数据结构。
1. 如何查看redis的数据结构?
1.1 如何查看redis的外部数据结构?
可以使用type命令,返回key的类型,如 string , list , set , zset , hash 和 stream,实例如下:
<pre style="box-sizing: border-box; font-family: monospace; font-size: 18px; margin: 20px 0px; padding: 15px; border: 0px; background-color: rgb(244, 245, 246); white-space: pre-wrap; word-break: break-all; color: rgb(34, 34, 34); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">redis> SET key1 "value"
"OK"
redis> LPUSH key2 "value"
(integer) 1
redis> SADD key3 "value"
(integer) 1
redis> TYPE key1
"string"
redis> TYPE key2
"list"
redis> TYPE key3
"set"
redis>
1.2 如何查看redis的内部数据结构
可以通过Object命令来查看。object命令允许从内部察看给定 <tt class="docutils literal" style="box-sizing: border-box;">key</tt> 的 Redis 对象。
它通常用在除错(debugging)或者了解为了节省空间而对 <tt class="docutils literal" style="box-sizing: border-box;">key</tt> 使用特殊编码的情况。
当将Redis用作缓存程序时,你也可以通过它命令中的信息,决定 <tt class="docutils literal" style="box-sizing: border-box;">key</tt> 的驱逐策略(eviction policies)。
2.redis数据结构的定义redisObject
内部数据类型server.h
<pre style="box-sizing: border-box; font-family: monospace; font-size: 18px; margin: 20px 0px; padding: 15px; border: 0px; background-color: rgb(244, 245, 246); white-space: pre-wrap; word-break: break-all; color: rgb(34, 34, 34); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">typedef struct redisObject {
unsigned type:4;
unsigned encoding:4;
unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
* LFU data (least significant 8 bits frequency
* and most significant 16 bits access time). */
int refcount;
void *ptr;
} robj;
其中,type为redis的外部数据结构,encoding为redis的内部数据结构实现
type的值如下:
<pre style="box-sizing: border-box; font-family: monospace; font-size: 18px; margin: 20px 0px; padding: 15px; border: 0px; background-color: rgb(244, 245, 246); white-space: pre-wrap; word-break: break-all; color: rgb(34, 34, 34); font-style: normal; font-variant-ligatures: normal; font-variant-caps: norma