Redis.md 23.2 KB
Newer Older
C
CyC2018 已提交
1 2 3
# 一、概述

Redis 是速度非常快的非关系型(NoSQL)内存键值数据库,可以存储键和五种不同类型的值之间的映射。
C
CyC2018 已提交
4

C
CyC2018 已提交
5
键的类型只能为字符串,值支持五种数据类型:字符串、列表、集合、散列表、有序集合。
C
CyC2018 已提交
6

C
CyC2018 已提交
7
Redis 支持很多特性,例如将内存中的数据持久化到硬盘中,使用复制来扩展读性能,使用分片来扩展写性能。
C
CyC2018 已提交
8

C
CyC2018 已提交
9
# 二、数据类型
C
CyC2018 已提交
10

C
CyC2018 已提交
11 12 13 14 15 16 17
| 数据类型 | 可以存储的值 | 操作 |
| :--: | :--: | :--: |
| STRING | 字符串、整数或者浮点数 | 对整个字符串或者字符串的其中一部分执行操作</br> 对整数和浮点数执行自增或者自减操作 |
| LIST | 列表 | 从两端压入或者弹出元素 </br> 对单个或者多个元素</br> 进行修剪,只保留一个范围内的元素 |
| SET | 无序集合 | 添加、获取、移除单个元素</br> 检查一个元素是否存在于集合中</br> 计算交集、并集、差集</br> 从集合里面随机获取元素 |
| HASH | 包含键值对的无序散列表 | 添加、获取、移除单个键值对</br> 获取所有键值对</br> 检查某个键是否存在|
| ZSET | 有序集合 | 添加、获取、删除元素</br> 根据分值范围或者成员来获取元素</br> 计算一个键的排名 |
C
CyC2018 已提交
18

C
CyC2018 已提交
19
> [What Redis data structures look like](https://redislabs.com/ebook/part-1-getting-started/chapter-1-getting-to-know-redis/1-2-what-redis-data-structures-look-like/)
C
CyC2018 已提交
20

C
CyC2018 已提交
21
## STRING
C
CyC2018 已提交
22

C
CyC2018 已提交
23
<img src="index_files/6019b2db-bc3e-4408-b6d8-96025f4481d6.png" width="400"/>
C
CyC2018 已提交
24 25

```html
C
CyC2018 已提交
26
> set hello world
C
CyC2018 已提交
27
OK
C
CyC2018 已提交
28
> get hello
C
CyC2018 已提交
29
"world"
C
CyC2018 已提交
30 31 32
> del hello
(integer) 1
> get hello
C
CyC2018 已提交
33 34 35
(nil)
```

C
CyC2018 已提交
36
## LIST
C
CyC2018 已提交
37

C
CyC2018 已提交
38
<img src="index_files/fb327611-7e2b-4f2f-9f5b-38592d408f07.png" width="400"/>
C
CyC2018 已提交
39 40

```html
C
CyC2018 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53
> rpush list-key item
(integer) 1
> rpush list-key item2
(integer) 2
> rpush list-key item
(integer) 3

> lrange list-key 0 -1
1) "item"
2) "item2"
3) "item"

> lindex list-key 1
C
CyC2018 已提交
54 55
"item2"

C
CyC2018 已提交
56
> lpop list-key
C
CyC2018 已提交
57 58
"item"

C
CyC2018 已提交
59 60 61
> lrange list-key 0 -1
1) "item2"
2) "item"
C
CyC2018 已提交
62 63
```

C
CyC2018 已提交
64
## SET
C
CyC2018 已提交
65

C
CyC2018 已提交
66
<img src="index_files/cd5fbcff-3f35-43a6-8ffa-082a93ce0f0e.png" width="400"/>
C
CyC2018 已提交
67 68

```html
C
CyC2018 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
> sadd set-key item
(integer) 1
> sadd set-key item2
(integer) 1
> sadd set-key item3
(integer) 1
> sadd set-key item
(integer) 0

> smembers set-key
1) "item"
2) "item2"
3) "item3"

> sismember set-key item4
(integer) 0
> sismember set-key item
(integer) 1

> srem set-key item2
(integer) 1
> srem set-key item2
(integer) 0

> smembers set-key
1) "item"
2) "item3"
C
CyC2018 已提交
96 97
```

C
CyC2018 已提交
98
## HASH
C
CyC2018 已提交
99

C
CyC2018 已提交
100
<img src="index_files/7bd202a7-93d4-4f3a-a878-af68ae25539a.png" width="400"/>
C
CyC2018 已提交
101 102

```html
C
CyC2018 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
> hset hash-key sub-key1 value1
(integer) 1
> hset hash-key sub-key2 value2
(integer) 1
> hset hash-key sub-key1 value1
(integer) 0

> hgetall hash-key
1) "sub-key1"
2) "value1"
3) "sub-key2"
4) "value2"

> hdel hash-key sub-key2
(integer) 1
> hdel hash-key sub-key2
(integer) 0

> hget hash-key sub-key1
C
CyC2018 已提交
122 123
"value1"

C
CyC2018 已提交
124 125 126
> hgetall hash-key
1) "sub-key1"
2) "value1"
C
CyC2018 已提交
127 128
```

C
CyC2018 已提交
129
## ZSET
C
CyC2018 已提交
130

C
CyC2018 已提交
131
<img src="index_files/1202b2d6-9469-4251-bd47-ca6034fb6116.png" width="400"/>
C
CyC2018 已提交
132 133

```html
C
CyC2018 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
> zadd zset-key 728 member1
(integer) 1
> zadd zset-key 982 member0
(integer) 1
> zadd zset-key 982 member0
(integer) 0

> zrange zset-key 0 -1 withscores
1) "member1"
2) "728"
3) "member0"
4) "982"

> zrangebyscore zset-key 0 800 withscores
1) "member1"
2) "728"

> zrem zset-key member1
(integer) 1
> zrem zset-key member1
(integer) 0

> zrange zset-key 0 -1 withscores
1) "member0"
2) "982"
C
CyC2018 已提交
159 160
```

C
CyC2018 已提交
161
# 三、数据结构
C
CyC2018 已提交
162

C
CyC2018 已提交
163
## 字典
C
CyC2018 已提交
164

C
CyC2018 已提交
165
dictht 是一个散列表结构,使用拉链法保存哈希冲突。
C
CyC2018 已提交
166 167

```c
C
CyC2018 已提交
168 169 170 171 172 173 174 175
/* This is our hash table structure. Every dictionary has two of this as we
 * implement incremental rehashing, for the old to the new table. */
typedef struct dictht {
    dictEntry **table;
    unsigned long size;
    unsigned long sizemask;
    unsigned long used;
} dictht;
C
CyC2018 已提交
176 177 178
```

```c
C
CyC2018 已提交
179 180 181 182 183 184 185 186 187 188
typedef struct dictEntry {
    void *key;
    union {
        void *val;
        uint64_t u64;
        int64_t s64;
        double d;
    } v;
    struct dictEntry *next;
} dictEntry;
C
CyC2018 已提交
189 190
```

C
CyC2018 已提交
191
Redis 的字典 dict 中包含两个哈希表 dictht,这是为了方便进行 rehash 操作。在扩容时,将其中一个 dictht 上的键值对 rehash 到另一个 dictht 上面,完成之后释放空间并交换两个 dictht 的角色。
C
CyC2018 已提交
192 193

```c
C
CyC2018 已提交
194 195 196 197 198 199 200
typedef struct dict {
    dictType *type;
    void *privdata;
    dictht ht[2];
    long rehashidx; /* rehashing not in progress if rehashidx == -1 */
    unsigned long iterators; /* number of iterators currently running */
} dict;
C
CyC2018 已提交
201
```
C
CyC2018 已提交
202

C
CyC2018 已提交
203
rehash 操作不是一次性完成,而是采用渐进方式,这是为了避免一次性执行过多的 rehash 操作给服务器带来过大的负担。
C
CyC2018 已提交
204

C
CyC2018 已提交
205
渐进式 rehash 通过记录 dict 的 rehashidx 完成,它从 0 开始,然后每执行一次 rehash 都会递增。例如在一次 rehash 中,要把 dict[0] rehash 到 dict[1],这一次会把 dict[0] 上 table[rehashidx] 的键值对 rehash 到 dict[1] 上,dict[0] 的 table[rehashidx] 指向 null,并令 rehashidx++。
C
CyC2018 已提交
206

C
CyC2018 已提交
207
在 rehash 期间,每次对字典执行添加、删除、查找或者更新操作时,都会执行一次渐进式 rehash。
C
CyC2018 已提交
208

C
CyC2018 已提交
209
采用渐进式 rehash 会导致字典中的数据分散在两个 dictht 上,因此对字典的查找操作也需要到对应的 dictht 去执行。
C
CyC2018 已提交
210 211

```c
C
CyC2018 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
/* Performs N steps of incremental rehashing. Returns 1 if there are still
 * keys to move from the old to the new hash table, otherwise 0 is returned.
 *
 * Note that a rehashing step consists in moving a bucket (that may have more
 * than one key as we use chaining) from the old to the new hash table, however
 * since part of the hash table may be composed of empty spaces, it is not
 * guaranteed that this function will rehash even a single bucket, since it
 * will visit at max N*10 empty buckets in total, otherwise the amount of
 * work it does would be unbound and the function may block for a long time. */
int dictRehash(dict *d, int n) {
    int empty_visits = n * 10; /* Max number of empty buckets to visit. */
    if (!dictIsRehashing(d)) return 0;

    while (n-- && d->ht[0].used != 0) {
        dictEntry *de, *nextde;

        /* Note that rehashidx can't overflow as we are sure there are more
         * elements because ht[0].used != 0 */
        assert(d->ht[0].size > (unsigned long) d->rehashidx);
        while (d->ht[0].table[d->rehashidx] == NULL) {
            d->rehashidx++;
            if (--empty_visits == 0) return 1;
        }
        de = d->ht[0].table[d->rehashidx];
        /* Move all the keys in this bucket from the old to the new hash HT */
        while (de) {
            uint64_t h;

            nextde = de->next;
            /* Get the index in the new hash table */
            h = dictHashKey(d, de->key) & d->ht[1].sizemask;
            de->next = d->ht[1].table[h];
            d->ht[1].table[h] = de;
            d->ht[0].used--;
            d->ht[1].used++;
            de = nextde;
        }
        d->ht[0].table[d->rehashidx] = NULL;
        d->rehashidx++;
    }

    /* Check if we already rehashed the whole table... */
    if (d->ht[0].used == 0) {
        zfree(d->ht[0].table);
        d->ht[0] = d->ht[1];
        _dictReset(&d->ht[1]);
        d->rehashidx = -1;
        return 0;
    }

    /* More to rehash... */
    return 1;
C
CyC2018 已提交
264 265 266
}
```

C
CyC2018 已提交
267
## 跳跃表
C
CyC2018 已提交
268 269 270 271 272

是有序集合的底层实现之一。

跳跃表是基于多指针有序链表实现的,可以看成多个有序链表。

C
CyC2018 已提交
273
<img src="index_files/beba612e-dc5b-4fc2-869d-0b23408ac90a.png" width="600px"/>
C
CyC2018 已提交
274

C
CyC2018 已提交
275
在查找时,从上层指针开始查找,找到对应的区间之后再到下一层去查找。下图演示了查找 22 的过程。
C
CyC2018 已提交
276

C
CyC2018 已提交
277
<img src="index_files/0ea37ee2-c224-4c79-b895-e131c6805c40.png" width="600px"/>
C
CyC2018 已提交
278 279 280

与红黑树等平衡树相比,跳跃表具有以下优点:

C
CyC2018 已提交
281 282 283
- 插入速度非常快速,因为不需要进行旋转等操作来维护平衡性;
- 更容易实现;
- 支持无锁操作。
C
CyC2018 已提交
284

C
CyC2018 已提交
285
# 四、使用场景
C
CyC2018 已提交
286

C
CyC2018 已提交
287
## 计数器
C
CyC2018 已提交
288

C
CyC2018 已提交
289
可以对 String 进行自增自减运算,从而实现计数器功能。
C
CyC2018 已提交
290

C
CyC2018 已提交
291
Redis 这种内存型数据库的读写性能非常高,很适合存储频繁读写的计数量。
C
CyC2018 已提交
292

C
CyC2018 已提交
293
## 缓存
C
CyC2018 已提交
294

C
CyC2018 已提交
295
将热点数据放到内存中,设置内存的最大使用量以及淘汰策略来保证缓存的命中率。
C
CyC2018 已提交
296

C
CyC2018 已提交
297
## 查找表
C
CyC2018 已提交
298

C
CyC2018 已提交
299
例如 DNS 记录就很适合使用 Redis 进行存储。
C
CyC2018 已提交
300

C
CyC2018 已提交
301
查找表和缓存类似,也是利用了 Redis 快速的查找特性。但是查找表的内容不能失效,而缓存的内容可以失效,因为缓存不作为可靠的数据来源。
C
CyC2018 已提交
302

C
CyC2018 已提交
303
## 消息队列
C
CyC2018 已提交
304

C
CyC2018 已提交
305
List 是一个双向链表,可以通过 lpop 和 lpush 写入和读取消息。
C
CyC2018 已提交
306

C
CyC2018 已提交
307
不过最好使用 Kafka、RabbitMQ 等消息中间件。
C
CyC2018 已提交
308

C
CyC2018 已提交
309
## 会话缓存
C
CyC2018 已提交
310

C
CyC2018 已提交
311
可以使用 Redis 来统一存储多台应用服务器的会话信息。
C
CyC2018 已提交
312

C
CyC2018 已提交
313
当应用服务器不再存储用户的会话信息,也就不再具有状态,一个用户可以请求任意一个应用服务器,从而更容易实现高可用性以及可伸缩性。
C
CyC2018 已提交
314

C
CyC2018 已提交
315
## 分布式锁实现
C
CyC2018 已提交
316

C
CyC2018 已提交
317
在分布式场景下,无法使用单机环境下的锁来对多个节点上的进程进行同步。
C
CyC2018 已提交
318

C
CyC2018 已提交
319
可以使用 Reids 自带的 SETNX 命令实现分布式锁,除此之外,还可以使用官方提供的 RedLock 分布式锁实现。
C
CyC2018 已提交
320

C
CyC2018 已提交
321
## 其它
C
CyC2018 已提交
322

C
CyC2018 已提交
323
Set 可以实现交集、并集等操作,从而实现共同好友等功能。
C
CyC2018 已提交
324

C
CyC2018 已提交
325
ZSet 可以实现有序性操作,从而实现排行榜等功能。
C
CyC2018 已提交
326

C
CyC2018 已提交
327
# 五、Redis 与 Memcached
C
CyC2018 已提交
328

C
CyC2018 已提交
329
两者都是非关系型内存键值数据库,主要有以下不同:
C
CyC2018 已提交
330

C
CyC2018 已提交
331
## 数据类型
C
CyC2018 已提交
332

C
CyC2018 已提交
333
Memcached 仅支持字符串类型,而 Redis 支持五种不同的数据类型,可以更灵活地解决问题。
C
CyC2018 已提交
334

C
CyC2018 已提交
335
## 数据持久化
C
CyC2018 已提交
336

C
CyC2018 已提交
337
Redis 支持两种持久化策略:RDB 快照和 AOF 日志,而 Memcached 不支持持久化。
C
CyC2018 已提交
338

C
CyC2018 已提交
339
## 分布式
C
CyC2018 已提交
340

C
CyC2018 已提交
341
Memcached 不支持分布式,只能通过在客户端使用一致性哈希来实现分布式存储,这种方式在存储和查询时都需要先在客户端计算一次数据所在的节点。
C
CyC2018 已提交
342

C
CyC2018 已提交
343
Redis Cluster 实现了分布式的支持。
C
CyC2018 已提交
344

C
CyC2018 已提交
345
## 内存管理机制
C
CyC2018 已提交
346

C
CyC2018 已提交
347
- 在 Redis 中,并不是所有数据都一直存储在内存中,可以将一些很久没用的 value 交换到磁盘,而 Memcached 的数据则会一直在内存中。
C
CyC2018 已提交
348

C
CyC2018 已提交
349
- Memcached 将内存分割成特定长度的块来存储数据,以完全解决内存碎片的问题。但是这种方式会使得内存的利用率不高,例如块的大小为 128 bytes,只存储 100 bytes 的数据,那么剩下的 28 bytes 就浪费掉了。
C
CyC2018 已提交
350

C
CyC2018 已提交
351
# 六、键的过期时间
C
CyC2018 已提交
352

C
CyC2018 已提交
353
Redis 可以为每个键设置过期时间,当键过期时,会自动删除该键。
C
CyC2018 已提交
354 355 356

对于散列表这种容器,只能为整个键设置过期时间(整个散列表),而不能为键里面的单个元素设置过期时间。

C
CyC2018 已提交
357
# 七、数据淘汰策略
C
CyC2018 已提交
358

C
CyC2018 已提交
359 360
可以设置内存最大使用量,当内存使用量超出时,会施行数据淘汰策略。

C
CyC2018 已提交
361
Reids 具体有 6 种淘汰策略:
C
CyC2018 已提交
362

C
CyC2018 已提交
363 364 365 366 367 368 369 370
| 策略 | 描述 |
| :--: | :--: |
| volatile-lru | 从已设置过期时间的数据集中挑选最近最少使用的数据淘汰 |
| volatile-ttl | 从已设置过期时间的数据集中挑选将要过期的数据淘汰 |
|volatile-random | 从已设置过期时间的数据集中任意选择数据淘汰 |
| allkeys-lru | 从所有数据集中挑选最近最少使用的数据淘汰 |
| allkeys-random | 从所有数据集中任意选择数据进行淘汰 |
| noeviction | 禁止驱逐数据 |
C
CyC2018 已提交
371

C
CyC2018 已提交
372
作为内存数据库,出于对性能和内存消耗的考虑,Redis 的淘汰算法实际实现上并非针对所有 key,而是抽样一小部分并且从中选出被淘汰的 key。
C
CyC2018 已提交
373

C
CyC2018 已提交
374
使用 Redis 缓存数据时,为了提高缓存命中率,需要保证缓存数据都是热点数据。可以将内存最大使用量设置为热点数据占用的内存量,然后启用 allkeys-lru 淘汰策略,将最近最少使用的数据淘汰。
C
CyC2018 已提交
375

C
CyC2018 已提交
376
Redis 4.0 引入了 volatile-lfu 和 allkeys-lfu 淘汰策略,LFU 策略通过统计访问频率,将访问频率最少的键值对淘汰。
C
CyC2018 已提交
377

C
CyC2018 已提交
378
# 八、持久化
C
CyC2018 已提交
379

C
CyC2018 已提交
380
Redis 是内存型数据库,为了保证数据在断电后不会丢失,需要将内存中的数据持久化到硬盘上。
C
CyC2018 已提交
381

C
CyC2018 已提交
382
## RDB 持久化
C
CyC2018 已提交
383 384 385 386 387 388 389 390 391

将某个时间点的所有数据都存放到硬盘上。

可以将快照复制到其它服务器从而创建具有相同数据的服务器副本。

如果系统发生故障,将会丢失最后一次创建快照之后的数据。

如果数据量很大,保存快照的时间会很长。

C
CyC2018 已提交
392
## AOF 持久化
C
CyC2018 已提交
393

C
CyC2018 已提交
394
将写命令添加到 AOF 文件(Append Only File)的末尾。
C
CyC2018 已提交
395

C
CyC2018 已提交
396
使用 AOF 持久化需要设置同步选项,从而确保写命令什么时候会同步到磁盘文件上。这是因为对文件进行写入并不会马上将内容同步到磁盘上,而是先存储到缓冲区,然后由操作系统决定什么时候同步到磁盘。有以下同步选项:
C
CyC2018 已提交
397

C
CyC2018 已提交
398 399 400 401 402
| 选项 | 同步频率 |
| :--: | :--: |
| always | 每个写命令都同步 |
| everysec | 每秒同步一次 |
| no | 让操作系统来决定何时同步 |
C
CyC2018 已提交
403

C
CyC2018 已提交
404 405 406
- always 选项会严重减低服务器的性能;
- everysec 选项比较合适,可以保证系统崩溃时只会丢失一秒左右的数据,并且 Redis 每秒执行一次同步对服务器性能几乎没有任何影响;
- no 选项并不能给服务器性能带来多大的提升,而且也会增加系统崩溃时数据丢失的数量。
C
CyC2018 已提交
407

C
CyC2018 已提交
408
随着服务器写请求的增多,AOF 文件会越来越大。Redis 提供了一种将 AOF 重写的特性,能够去除 AOF 文件中的冗余写命令。
C
CyC2018 已提交
409

C
CyC2018 已提交
410
# 九、事务
C
CyC2018 已提交
411

C
CyC2018 已提交
412
一个事务包含了多个命令,服务器在执行事务期间,不会改去执行其它客户端的命令请求。
C
CyC2018 已提交
413

C
CyC2018 已提交
414
事务中的多个命令被一次性发送给服务器,而不是一条一条发送,这种方式被称为流水线,它可以减少客户端与服务器之间的网络通信次数从而提升性能。
C
CyC2018 已提交
415

C
CyC2018 已提交
416
Redis 最简单的事务实现方式是使用 MULTI 和 EXEC 命令将事务操作包围起来。
C
CyC2018 已提交
417

C
CyC2018 已提交
418
# 十、事件
C
CyC2018 已提交
419

C
CyC2018 已提交
420
Redis 服务器是一个事件驱动程序。
C
CyC2018 已提交
421

C
CyC2018 已提交
422
## 文件事件
C
CyC2018 已提交
423

C
CyC2018 已提交
424
服务器通过套接字与客户端或者其它服务器进行通信,文件事件就是对套接字操作的抽象。
C
CyC2018 已提交
425

C
CyC2018 已提交
426
Redis 基于 Reactor 模式开发了自己的网络事件处理器,使用 I/O 多路复用程序来同时监听多个套接字,并将到达的事件传送给文件事件分派器,分派器会根据套接字产生的事件类型调用相应的事件处理器。
C
CyC2018 已提交
427

C
CyC2018 已提交
428
<img src="index_files/9ea86eb5-000a-4281-b948-7b567bd6f1d8.png" width=""/>
C
CyC2018 已提交
429

C
CyC2018 已提交
430
## 时间事件
C
CyC2018 已提交
431

C
CyC2018 已提交
432
服务器有一些操作需要在给定的时间点执行,时间事件是对这类定时操作的抽象。
C
CyC2018 已提交
433

C
CyC2018 已提交
434
时间事件又分为:
C
CyC2018 已提交
435

C
CyC2018 已提交
436 437
- 定时事件:是让一段程序在指定的时间之内执行一次;
- 周期性事件:是让一段程序每隔指定时间就执行一次。
C
CyC2018 已提交
438

C
CyC2018 已提交
439
Redis 将所有时间事件都放在一个无序链表中,通过遍历整个链表查找出已到达的时间事件,并调用相应的事件处理器。
C
CyC2018 已提交
440

C
CyC2018 已提交
441
## 事件的调度与执行
C
CyC2018 已提交
442

C
CyC2018 已提交
443
服务器需要不断监听文件事件的套接字才能得到待处理的文件事件,但是不能一直监听,否则时间事件无法在规定的时间内执行,因此监听时间应该根据距离现在最近的时间事件来决定。
C
CyC2018 已提交
444

C
CyC2018 已提交
445
事件调度与执行由 aeProcessEvents 函数负责,伪代码如下:
C
CyC2018 已提交
446 447

```python
C
CyC2018 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
def aeProcessEvents():
    # 获取到达时间离当前时间最接近的时间事件
    time_event = aeSearchNearestTimer()
    # 计算最接近的时间事件距离到达还有多少毫秒
    remaind_ms = time_event.when - unix_ts_now()
    # 如果事件已到达,那么 remaind_ms 的值可能为负数,将它设为 0
    if remaind_ms < 0:
        remaind_ms = 0
    # 根据 remaind_ms 的值,创建 timeval
    timeval = create_timeval_with_ms(remaind_ms)
    # 阻塞并等待文件事件产生,最大阻塞时间由传入的 timeval 决定
    aeApiPoll(timeval)
    # 处理所有已产生的文件事件
    procesFileEvents()
    # 处理所有已到达的时间事件
    processTimeEvents()
C
CyC2018 已提交
464 465
```

C
CyC2018 已提交
466
将 aeProcessEvents 函数置于一个循环里面,加上初始化和清理函数,就构成了 Redis 服务器的主函数,伪代码如下:
C
CyC2018 已提交
467 468

```python
C
CyC2018 已提交
469 470 471 472 473 474 475 476
def main():
    # 初始化服务器
    init_server()
    # 一直处理事件,直到服务器关闭为止
    while server_is_not_shutdown():
        aeProcessEvents()
    # 服务器关闭,执行清理操作
    clean_server()
C
CyC2018 已提交
477 478 479 480
```

从事件处理的角度来看,服务器运行流程如下:

C
CyC2018 已提交
481
<img src="index_files/c0a9fa91-da2e-4892-8c9f-80206a6f7047.png" width="350"/>
C
CyC2018 已提交
482

C
CyC2018 已提交
483
# 十一、复制
C
CyC2018 已提交
484

C
CyC2018 已提交
485
通过使用 slaveof host port 命令来让一个服务器成为另一个服务器的从服务器。
C
CyC2018 已提交
486

C
CyC2018 已提交
487
一个从服务器只能有一个主服务器,并且不支持主主复制。
C
CyC2018 已提交
488

C
CyC2018 已提交
489
## 连接过程
C
CyC2018 已提交
490

C
CyC2018 已提交
491
1. 主服务器创建快照文件,发送给从服务器,并在发送期间使用缓冲区记录执行的写命令。快照文件发送完毕之后,开始向从服务器发送存储在缓冲区中的写命令;
C
CyC2018 已提交
492

C
CyC2018 已提交
493
2. 从服务器丢弃所有旧数据,载入主服务器发来的快照文件,之后从服务器开始接受主服务器发来的写命令;
C
CyC2018 已提交
494

C
CyC2018 已提交
495
3. 主服务器每执行一次写命令,就向从服务器发送相同的写命令。
C
CyC2018 已提交
496

C
CyC2018 已提交
497
## 主从链
C
CyC2018 已提交
498

C
CyC2018 已提交
499
随着负载不断上升,主服务器可能无法很快地更新所有从服务器,或者重新连接和重新同步从服务器将导致系统超载。为了解决这个问题,可以创建一个中间层来分担主服务器的复制工作。中间层的服务器是最上层服务器的从服务器,又是最下层服务器的主服务器。
C
CyC2018 已提交
500

C
CyC2018 已提交
501
<img src="index_files/395a9e83-b1a1-4a1d-b170-d081e7bb5bab.png" width="600"/>
C
CyC2018 已提交
502

C
CyC2018 已提交
503
# 十二、Sentinel
C
CyC2018 已提交
504

C
CyC2018 已提交
505
Sentinel(哨兵)可以监听集群中的服务器,并在主服务器进入下线状态时,自动从从服务器中选举出新的主服务器。
C
CyC2018 已提交
506

C
CyC2018 已提交
507
# 十三、分片
C
CyC2018 已提交
508

C
CyC2018 已提交
509
分片是将数据划分为多个部分的方法,可以将数据存储到多台机器里面,这种方法在解决某些问题时可以获得线性级别的性能提升。
C
CyC2018 已提交
510

C
CyC2018 已提交
511
假设有 4 个 Reids 实例 R0,R1,R2,R3,还有很多表示用户的键 user:1,user:2,... ,有不同的方式来选择一个指定的键存储在哪个实例中。
C
CyC2018 已提交
512

C
CyC2018 已提交
513 514
- 最简单的方式是范围分片,例如用户 id 从 0~1000 的存储到实例 R0 中,用户 id 从 1001~2000 的存储到实例 R1 中,等等。但是这样需要维护一张映射范围表,维护操作代价很高。
- 还有一种方式是哈希分片,使用 CRC32 哈希函数将键转换为一个数字,再对实例数量求模就能知道应该存储的实例。
C
CyC2018 已提交
515

C
CyC2018 已提交
516
根据执行分片的位置,可以分为三种分片方式:
C
CyC2018 已提交
517

C
CyC2018 已提交
518 519 520
- 客户端分片:客户端使用一致性哈希等算法决定键应当分布到哪个节点。
- 代理分片:将客户端请求发送到代理上,由代理转发请求到正确的节点上。
- 服务器分片:Redis Cluster。
C
CyC2018 已提交
521

C
CyC2018 已提交
522
# 十四、一个简单的论坛系统分析
C
CyC2018 已提交
523 524 525

该论坛系统功能如下:

C
CyC2018 已提交
526 527 528
- 可以发布文章;
- 可以对文章进行点赞;
- 在首页可以按文章的发布时间或者文章的点赞数进行排序显示。
C
CyC2018 已提交
529

C
CyC2018 已提交
530
## 文章信息
C
CyC2018 已提交
531

C
CyC2018 已提交
532
文章包括标题、作者、赞数等信息,在关系型数据库中很容易构建一张表来存储这些信息,在 Redis 中可以使用 HASH 来存储每种信息以及其对应的值的映射。
C
CyC2018 已提交
533

C
CyC2018 已提交
534
Redis 没有关系型数据库中的表这一概念来将同种类型的数据存放在一起,而是使用命名空间的方式来实现这一功能。键名的前面部分存储命名空间,后面部分的内容存储 ID,通常使用 : 来进行分隔。例如下面的 HASH 的键名为 article:92617,其中 article 为命名空间,ID 为 92617。
C
CyC2018 已提交
535

C
CyC2018 已提交
536
<img src="index_files/7c54de21-e2ff-402e-bc42-4037de1c1592.png" width="400"/>
C
CyC2018 已提交
537

C
CyC2018 已提交
538
## 点赞功能
C
CyC2018 已提交
539

C
CyC2018 已提交
540
当有用户为一篇文章点赞时,除了要对该文章的 votes 字段进行加 1 操作,还必须记录该用户已经对该文章进行了点赞,防止用户点赞次数超过 1。可以建立文章的已投票用户集合来进行记录。
C
CyC2018 已提交
541 542 543

为了节约内存,规定一篇文章发布满一周之后,就不能再对它进行投票,而文章的已投票集合也会被删除,可以为文章的已投票集合设置一个一周的过期时间就能实现这个规定。

C
CyC2018 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
<img src="index_files/485fdf34-ccf8-4185-97c6-17374ee719a0.png" width="400"/>

## 对文章进行排序

为了按发布时间和点赞数进行排序,可以建立一个文章发布时间的有序集合和一个文章点赞数的有序集合。(下图中的 score 就是这里所说的点赞数;下面所示的有序集合分值并不直接是时间和点赞数,而是根据时间和点赞数间接计算出来的)

<img src="index_files/f7d170a3-e446-4a64-ac2d-cb95028f81a8.png" width="800"/>

# 参考资料

- Carlson J L. Redis in Action[J]. Media.johnwiley.com.au, 2013.
[黄健宏. Redis 设计与实现 [M]. 机械工业出版社, 2014.](http://redisbook.com/index.html)
[REDIS IN ACTION](https://redislabs.com/ebook/foreword/)
[Skip Lists: Done Right](http://ticki.github.io/blog/skip-lists-done-right/)
[论述 Redis 和 Memcached 的差异](http://www.cnblogs.com/loveincode/p/7411911.html)
[Redis 3.0 中文版- 分片](http://wiki.jikexueyuan.com/project/redis-guide)
[Redis 应用场景](http://www.scienjus.com/redis-use-case/)
[Using Redis as an LRU cache](https://redis.io/topics/lru-cache)
---bottom---CyC---
![](index_files/6019b2db-bc3e-4408-b6d8-96025f4481d6.png)
![](index_files/fb327611-7e2b-4f2f-9f5b-38592d408f07.png)
![](index_files/cd5fbcff-3f35-43a6-8ffa-082a93ce0f0e.png)
![](index_files/7bd202a7-93d4-4f3a-a878-af68ae25539a.png)
![](index_files/1202b2d6-9469-4251-bd47-ca6034fb6116.png)
![](index_files/beba612e-dc5b-4fc2-869d-0b23408ac90a.png)
![](index_files/0ea37ee2-c224-4c79-b895-e131c6805c40.png)
![](index_files/9ea86eb5-000a-4281-b948-7b567bd6f1d8.png)
![](index_files/c0a9fa91-da2e-4892-8c9f-80206a6f7047.png)
![](index_files/395a9e83-b1a1-4a1d-b170-d081e7bb5bab.png)
![](index_files/7c54de21-e2ff-402e-bc42-4037de1c1592.png)
![](index_files/485fdf34-ccf8-4185-97c6-17374ee719a0.png)
![](index_files/f7d170a3-e446-4a64-ac2d-cb95028f81a8.png)