本篇主要内容:

1.安装Redis及Ruby环境

一.安装Redis及Ruby环境

1.前言

  这里注意:我们这里搭建的Redis集群有 3 个节点,每个节点包括两个Redis实例(这两个是主从复制的),就是说我们一共需要有 6 个Redis实例。

  • 建议在三台主机上搭建该集群,每台主机拥有一个主从复制节点。
  • 当然,你也可以在一台主机的 6 个不同的端口搭建该集群。

2.安装Redis

  • 如果你使用的是多台主机,则需要在每台主机上都安装 Redis。
  • ①安装编译环境:
1
yum install -y gcc-c++
1
2
cd /opt/
wget https://download.redis.io/releases/redis-6.2.1.tar.gz
  • ③解压源码:
1
tar -zxvf redis-6.2.1.tar.gz
  • ④编译:
1
2
cd /opt/redis-6.2.1
make
  • ⑤安装:
1
2
3
4
5
6
7
8
9
make install PREFIX=/usr/local/redis
# 进入安装目录,使用 redis-cli 测试即可
cd /usr/local/redis/bin
# 执行下面命令会提示:
# Could not connect to Redis at 127.0.0.1:6379: Connection refused
./redis-cli

# 可以将redis的可执行文件链接到 /usr/bin/ 使之成为全局命令
ln -s /usr/local/redis/bin/* /usr/bin/
  • ⑥启动一个Redis实例:

  通过这里我们知道使用 redis-server 一个 *.conf 即可启动一个 Redis 实例,因此,我们可以在一台主机上搭建出 Redis 伪集群。

  • 只需要有 6 个不同的 conf 文件即可。conf 文件的配置详解:Redis 配置
1
2
3
4
# ①直接启动一个默认的Redis
/usr/local/redis/bin/redis-server
# ②通过配置文件启动一个Redis
/usr/local/redis/bin/redis-server /opt/redis-6.2.1/redis.conf

3.安装Ruby

  • 注意:若是 Redis 5.0 之后的版本,可以直接使用redis-cli命令创建集群,而不需要用 redis-trib.rb,也不用安装 Ruby 环境。
  • 注意:你可以使用yum安装低版本的 Ruby,高版本的请直接参看 源码安装Ruby
1
2
3
4
5
6
yum install ruby
yum install rubygems
# 在线安装 redis*.gem 很可能会报错,它默认安装最新版的 gem
gem install redis
# 当然你可以下载离线版的 gem,之后离线安装
gem install -f redis-*.*.*.gem

二.Redis配置

1. redis.conf

  • redis.conf 配置文件所有内容如下:
redis.conf 配置文件: 👇
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# Redis 服务启动命令
# ./redis-server /path/to/redis.conf
################################## INCLUDES ###################################
# 引入其他配置文件
# include /path/to/local.conf
# include /path/to/other.conf

################################## MODULES #####################################
# 启动时加载的模块
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so

################################## NETWORK #####################################
# bind 192.168.1.100 10.0.0.1 # l监听两个特定的 IPv4 地址
# bind 127.0.0.1 ::1 # 监听本地 IPv4 和 IPv6 回环地址
# bind * -::* # 监听所有网卡 # 旧版 Redis 不支持
bind 127.0.0.1 -::1

# 启用保护模式,禁止公网访问。启用的条件:没使用bind 或 没设置访问密码
protected-mode yes

# 设置 Redis 服务端口
port 6379

# TCP 队列数。在高并发环境下 该值与 超时时间内 Redis 的吞吐量有关
tcp-backlog 511

# Unix socket 路径
# unixsocket /run/redis.sock
# 访问权限
# unixsocketperm 700

# 当客户端闲置多少秒后关闭连接,0表示永不关闭
timeout 0

# 每隔 300s 会对客户端进行心跳检测
tcp-keepalive 300

################################# TLS/SSL #####################################
################################# GENERAL #####################################
# 是否以守护模式启动,默认为no
daemonize yes
# 是否可以通过 upstart 和 systemd 管理 Redis 守护进程
# supervised auto
# pid 文件
pidfile /var/run/redis_6379.pid
# 日志级别
loglevel notice
# 日志文件名
logfile ""
# 数据库数量
databases 16
# 是否总是打印显示 logo
always-show-logo no
# 设置进程名/标题 # 旧版 Redis 不支持
set-proc-title yes
# 模板 # 旧版 Redis 不支持
proc-title-template "{title} {listen-addr} {server-mode}"

################################ SNAPSHOTTING ################################
# save <seconds> <changes>
# 数据持久化,在 seconds 秒内至少有 changes 个keys 发生改变则触发保存
# save 3600 1
# save 300 100
# save 60 10000
# 当后台持久化出错时,停止接受写操作
stop-writes-on-bgsave-error yes

# RDB 持久化模式是否压缩存储
rdbcompression yes

# 是否CRC64校验rdb文件
rdbchecksum yes

# RDB 持久化的文件名
dbfilename dump.rdb

# rdb文件 是否删除同步锁
rdb-del-sync-files no

# 数据库存放目录
dir ./

################################# REPLICATION #################################
# 设置本机为 slave
# slaveof <masterip> <masterport>
# replicaof <masterip> <masterport>

# master 的密码
# masterauth <master-password>
# master 的用户名
# masteruser <username>
# AUTH <username> <password>.

# 当slave与master失去联系 或 正在复制时,slave 仍应答客户端请求,但返回的数据可能不对
replica-serve-stale-data yes

# 设置 slave 只读
replica-read-only yes

# 是否使用 socket 进行数据同步
repl-diskless-sync no

# socket 进行数据同步延迟时间
repl-diskless-sync-delay 5

# 是否使用无磁盘加载
# "disabled" - 不要使用无磁盘加载,先将rdb文件存储到磁盘
# "on-empty-db" - 只有在完全安全的情况下才使用无磁盘加载
# "swapdb" - 解析时在 RAM 中保留当前db内容的副本,直接从 socket 获取数据
repl-diskless-load disabled

# 指定slave定期ping master的周期
# repl-ping-replica-period 10

# 从服务ping主服务的超时时间
# repl-timeout 60

# master 立即发送同步数据,没有延迟
repl-disable-tcp-nodelay no

# 主从复制backlog容量大小
# repl-backlog-size 1mb

# 配置当master和slave失去联系多少秒之后,清空backlog释放空间
# repl-backlog-ttl 3600

# 当 master 宕机时,Redis Sentinel 会从 slaves 中选出一个新的 master,
# 该值越小,越会被优先选中,0 表示永远不可能被选中。 默认优先级为 100
replica-priority 100

# 若主redis发现有超过 3 个从redis的连接延时大于 10 秒,那么主redis就停止接受外来的写请求
# min-replicas-to-write 3
# min-replicas-max-lag 10

# 常用于端口转发或NAT场景下,对Master暴露真实IP和端口信息
# replica-announce-ip 5.5.5.5
# replica-announce-port 1234

############################### KEYS TRACKING #################################
################################## SECURITY ###################################
# ACL 日志存储在内存中并消耗内存,设置此项可以设置最大值来回收内存
acllog-max-len 128

# ACL 文件
# aclfile /etc/redis/users.acl

# 设置访问密码
# requirepass foobared

# 为了安全考虑,可以将某些重要的、危险的命令重命名。当你把某个命令重命名成空字符串的时候就等于取消了这个命令。
# rename-command CONFIG ""

################################### CLIENTS ####################################
# 客户端最大连接数
# maxclients 10000
############################## MEMORY MANAGEMENT ################################
# Redis 能使用的最大内存
# maxmemory <bytes>

# Redis达到最大内存时将如何选择要删除的内容:
# volatile-lru -> Evict using approximated LRU, only keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU, only keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key having an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# maxmemory-policy noeviction

# 设置样本,从 5 个样本中选出一个 KEY 进行移除
# maxmemory-samples 5

# 从机忽略内存删除策略,只有 master 才会执行过期删除策略
# replica-ignore-maxmemory yes

############################# LAZY FREEING ####################################
# 内存超限,是否采用lazy free机制
lazyfree-lazy-eviction no
# 针对 TTL 的键,达到过期后,被redis清理删除时是否采用lazy free机制
lazyfree-lazy-expire no
# 处理已存在的键时,隐式的DEL键的操作是否采用lazy free机制
lazyfree-lazy-server-del no
# 是否采用异常flush机制
replica-lazy-flush no
lazyfree-lazy-user-del no
# 旧版 Redis 不支持
lazyfree-lazy-user-flush no

################################ THREADED I/O #################################
############################ KERNEL OOM CONTROL ##############################
oom-score-adj no
oom-score-adj-values 0 200 800

#################### KERNEL transparent hugepage CONTROL ######################
# 旧版 Redis 不支持
disable-thp yes

############################## APPEND ONLY MODE ###############################
# 是否启用 AOF 持久化方式
appendonly no

# 持久化文件名
appendfilename "appendonly.aof"

# AOF 文件刷新的频率
appendfsync everysec
# appendfsync no

# 是否在后台 AOF 文件rewrite期间调用fsync
no-appendfsync-on-rewrite no

# aof 文件增长比例,指当前 aof 文件比上次重写的增长比例大小
auto-aof-rewrite-percentage 100
# aof 文件重写最小的文件大小,AOF 文件达到 64 mb 会重写 AOF 文件
auto-aof-rewrite-min-size 64mb

# redis在恢复时,会忽略最后一条可能存在问题的指令
aof-load-truncated yes

# AOF重写产生的文件将同时包含RDB格式的内容和AOF格式的内容
# 兼有RDB持久化和AOF持久化
aof-use-rdb-preamble yes

################################ LUA SCRIPTING LUA 脚本 ###############################
# 一个Lua脚本最长的执行时间 ms
lua-time-limit 5000

################################ REDIS CLUSTER ###############################
# 是否启用集群
# cluster-enabled yes

# 用户不可编辑的 conf
# 该文件是Redis集群节点自动持久化每次配置的改变,以便在启动的时重新读取它
# cluster-config-file nodes-6379.conf

# 集群节点不可用的最大时间
# cluster-node-timeout 15000

# 最大失去连接的时间:cluster-node-timeout * cluster-replica-validity-factor
# cluster-replica-validity-factor 10

# 至少与其它多少slave保持连接的slave才有资格成为master
# cluster-migration-barrier 1

# no表示,当一个插槽节点不工作,则该槽位停止接收查询操作,集群仍然正常工作,如果为yes,则任意一个槽位不可用则整个集群不可用
# cluster-require-full-coverage yes

# 禁止主服务器转移
# cluster-replica-no-failover no

# 是否允许集群在宕机时读取
# cluster-allow-reads-when-down no

########################## CLUSTER DOCKER/NAT support ########################
# 宣布IP地址
# cluster-announce-ip 10.1.1.5
# 宣布服务端口
# cluster-announce-port 6379
# 宣布集群总线端口
# cluster-announce-bus-port 6380

################################## SLOW LOG ###################################
# 对执行时间大于多少微秒(microsecond,1秒 = 1,000,000 微秒)的查询进行记录
slowlog-log-slower-than 10000

# slow log 最多能保存多少条日志
slowlog-max-len 128

################################ LATENCY MONITOR ##############################
# 设置一个毫秒单位的延时阈值来开启延时监控
latency-monitor-threshold 0

############################# EVENT NOTIFICATION ##############################
notify-keyspace-events ""

############################### GOPHER SERVER #################################
# 是否开启gopher功能
# gopher-enabled no

############################### ADVANCED CONFIG ###############################
# ziplist 中允许存储的最大条目个数
hash-max-ziplist-entries 512
# ziplist 中允许条目value值最大字节数
hash-max-ziplist-value 64

# -5: max size: 64 Kb <-- not recommended for normal workloads
# -4: max size: 32 Kb <-- not recommended
# -3: max size: 16 Kb <-- probably not recommended
# -2: max size: 8 Kb <-- good
# -1: max size: 4 Kb <-- good
# ziplist 列表最大值
list-max-ziplist-size -2

# 一个 quicklist 两端不被压缩的节点个数
list-compress-depth 0

# 当集合中的元素全是整数,且长度不超过set-max-intset-entries(默认为512个)时,redis会选用intset作为内部编码,大于512用set
set-max-intset-entries 512

# 当有序集合元素个数小于zset-max-ziplist-entries配置(默认128),同时每个元素的值都小于zset-max-ziplist-value(默认是64B)时,
# Redis会用ziplist来作为有序集合的内部编码实现,ziplist可以有效的减少内存的使用
zset-max-ziplist-entries 128
zset-max-ziplist-value 64

hll-sparse-max-bytes 3000

stream-node-max-bytes 4096
stream-node-max-entries 100

activerehashing yes

client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60

# client-query-buffer-limit 1gb

# proto-max-bulk-len 512mb

hz 10

dynamic-hz yes

aof-rewrite-incremental-fsync yes

rdb-save-incremental-fsync yes

# lfu-log-factor 10
# lfu-decay-time 1

########################### ACTIVE DEFRAGMENTATION #######################
# Enabled active defragmentation
# activedefrag no

# Minimum amount of fragmentation waste to start active defrag
# active-defrag-ignore-bytes 100mb

# Minimum percentage of fragmentation to start active defrag
# active-defrag-threshold-lower 10

# Maximum percentage of fragmentation at which we use maximum effort
# active-defrag-threshold-upper 100

# Minimal effort for defrag in CPU percentage, to be used when the lower
# threshold is reached
# active-defrag-cycle-min 1

# Maximal effort for defrag in CPU percentage, to be used when the upper
# threshold is reached
# active-defrag-cycle-max 25

# Maximum number of set/hash/zset/list fields that will be processed from
# the main dictionary scan
# active-defrag-max-scan-fields 1000

# Jemalloc background thread for purging will be enabled by default
jemalloc-bg-thread yes

# Set redis server/io threads to cpu affinity 0,2,4,6:
# server_cpulist 0-7:2
#
# Set bio threads to cpu affinity 1,3:
# bio_cpulist 1,3
#
# Set aof rewrite child process to cpu affinity 8,9,10,11:
# aof_rewrite_cpulist 8-11
#
# Set bgsave child process to cpu affinity 1,10,11
# bgsave_cpulist 1,10-11

# ignore-warnings ARM64-COW-BUG

2. Redis常用配置

  • 可以从 redis.conf 中提取出公共的配置,见:common.conf

  • 单个 Redis 实例的个性配置如下:

    • bind:要绑定的网络接口

    • port:Redis 服务端口

    • daemonize:是否后台运行

    • pidfile:存放进程 pid 的文件

    • loglevel:日志级别

    • logfile:日志文件名

    • dbfilename:RDB 持久化的文件名

    • dir:数据库存放目录

    • replica-priority:从机 的优先级

    • appendonly:是否启用 AOF 持久化

    • appendfilename:AOF 文件名

    • cluster-enabled:是否启用集群

    • cluster-config-file:集群节点配置文件

    • cluster-node-timeout:集群节点不可用的最大时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
include /opt/redis/common.conf
bind * -::*
port 7000
daemonize yes
pidfile /opt/redis/redis_7000.pid
loglevel notice
logfile "redis_7000.log"
dbfilename dump7000.rdb
dir /opt/redis/
replica-priority 100
appendonly no
appendfilename "appendonly7000.aof"
#cluster-enabled yes
#cluster-config-file nodes-7000.conf
#cluster-node-timeout 15000

3. common.conf

  • 将通用的配置抽取出来放到一个单独的 conf 文件中,之后,在其他各自的配置文件中 include 即可。
common.conf: 👇
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
96
97
98
99
100
101
102
103
104
105
106
107
108
################################## INCLUDES ###################################
################################## MODULES #####################################
################################## NETWORK #####################################
protected-mode yes
tcp-backlog 511
timeout 0
tcp-keepalive 300

################################# TLS/SSL #####################################
################################# GENERAL #####################################
databases 16
always-show-logo no
set-proc-title yes
proc-title-template "{title} {listen-addr} {server-mode}"

################################ SNAPSHOTTING ################################
# save 3600 1
# save 300 100
# save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
rdb-del-sync-files no

################################# REPLICATION #################################
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-diskless-load disabled
repl-disable-tcp-nodelay no

############################### KEYS TRACKING #################################
################################## SECURITY ###################################
acllog-max-len 128

################################### CLIENTS ####################################
############################## MEMORY MANAGEMENT ################################
############################# LAZY FREEING ####################################
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
lazyfree-lazy-user-del no
lazyfree-lazy-user-flush no

################################ THREADED I/O #################################
############################ KERNEL OOM CONTROL ##############################
oom-score-adj no
oom-score-adj-values 0 200 800

#################### KERNEL transparent hugepage CONTROL ######################
disable-thp yes

############################## APPEND ONLY MODE ###############################
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes

################################ LUA SCRIPTING LUA 脚本 ###############################
lua-time-limit 5000

################################ REDIS CLUSTER ###############################
########################## CLUSTER DOCKER/NAT support ########################
################################## SLOW LOG ###################################
slowlog-log-slower-than 10000

slowlog-max-len 128

################################ LATENCY MONITOR ##############################
latency-monitor-threshold 0
############################# EVENT NOTIFICATION ##############################
notify-keyspace-events ""
############################### GOPHER SERVER #################################
############################### ADVANCED CONFIG ###############################
hash-max-ziplist-entries 512
hash-max-ziplist-value 64

list-max-ziplist-size -2
list-compress-depth 0

set-max-intset-entries 512

zset-max-ziplist-entries 128
zset-max-ziplist-value 64

hll-sparse-max-bytes 3000

stream-node-max-bytes 4096
stream-node-max-entries 100

activerehashing yes

client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60

hz 10
dynamic-hz yes

aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes

# Jemalloc background thread for purging will be enabled by default
jemalloc-bg-thread yes

三.Redis集群

  注意:这里搭建的伪分布式集群,在一台主机上,redis-server 了六个不同的 conf 文件。

1.创建6个conf

  • ①执行命令:mkdir /opt/redis/conf/,创建配置文件存放目录。
  • ②将 common.conf 的内容复制到 /opt/redis/conf/common.conf中。
  • ③创建6个不同的 conf 文件。
1
2
3
4
5
6
touch /opt/redis/conf/redis7000.conf
touch /opt/redis/conf/redis7001.conf
touch /opt/redis/conf/redis7002.conf
touch /opt/redis/conf/redis7003.conf
touch /opt/redis/conf/redis7004.conf
touch /opt/redis/conf/redis7005.conf

2.集群配置

  • ①依次编辑 /opt/redis/conf/redis****.conf 等6个文件,添加下述内容(并将 xxxx 改为对应端口号):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
include /opt/redis/conf/common.conf
bind * -::*
port xxxx
daemonize yes
pidfile /opt/redis/redis_xxxx.pid
loglevel notice
logfile "redis_xxxx.log"
dbfilename dump_xxxx.rdb
dir /opt/redis/data/
replica-priority 100
appendonly no
appendfilename "appendonly_xxxx.aof"
# 开启集群
cluster-enabled yes
cluster-config-file nodes-xxxx.conf
cluster-node-timeout 15000
  • ②执行mkdir /opt/redis/data/ 命令。

  • ③使用 redis-server 命令启动6个 Redis 实例:

1
2
3
4
5
6
7
SHELL=/bin/bash
/usr/local/redis/bin/redis-server /opt/redis/conf/redis7000.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis7001.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis7002.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis7003.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis7004.conf
/usr/local/redis/bin/redis-server /opt/redis/conf/redis7005.conf
  • ④使用命令 ps -ef | grep redis 查看 Redis 服务是否启动成功。

Redis_000

3.使用命令搭建集群

  • 注意:我这里是用 Ubuntu 20.04 在本地搭建的 伪分布式集群。若是服务器或虚拟机,别忘了修改 IP 地址。

  • ①直接使用 redis-cli 命令创建集群:

1
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1

Redis_001

Redis_002

  • ②使用 Ruby 脚本创建集群:
1
2
3
4
5
6
7
# 移动脚本
cp /opt/redis-6.2.1/src/redis-trib.rb /opt/redis
cd /opt/redis
# 提权
chmod +x redis-trib.rb
# 创建集群
./redis-trib.rb create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005

4.测试集群

  • 使用命令:redis-cli -h 127.0.0.1 -p 7000 -c 连接,测试即可。
  • 注意:-h指定主机IP,-p指定端口号,-c表示连接集群。一定要加 -c

Redis_003


评论