1. 程式人生 > >Redis 配置檔案詳解

Redis 配置檔案詳解

Redis服務端配置檔案

################################ GENERAL 通用 #####################################

是否以守護程序方式後臺執行執行,預設no,前臺執行

daemonize no

開啟守護模式指定執行的程序號

pidfile /var/run/redis.pid

Redis 提供服務埠號,port = 0 標識redis不監聽TCP埠

port 6379

TCP listen() backlog.: TCP第一次握手最大待連結數

注意:確保/proc/sys/net/core/somaxconn tcp_max_syn_backlog升值,否則Linux核心預設按最小的來配置

tcp-backlog 511

Redis 伺服器地址繫結:不同1臺電腦在不同網路可能存在多個ip地址,預設127.0.0.1

bind 192.168.1.100 10.0.0.1

bind 127.0.0.1

指定Unix Socket檔案路徑

unixsocket /tmp/redis.sock

unixsocketperm 700

客戶端最長空閒時間,0標識不限制

timeout 0

TCP keepalive. TCP保活時間,主要防止客戶端故障,服務端還維護連結,浪費資源,類似心跳機制,推薦60s

tcp-keepalive 0

指定日誌等級:debug/verbose/notice/warning

loglevel verbose

指定守護程序模式日誌輸出檔案,預設/dev/null,非守護模式直接輸出到標準輸出

logfile ""

是否輸出到系統日誌

syslog-enabled no

指定系統日誌標識

syslog-ident redis

執行系統日誌特性,必須是使用者或者LOCAL0-LOCAL7之間

syslog-facility local0

設定資料庫數量,預設使用DB0,可通過select <dbid>切換資料庫

databases 16

################################ SNAPSHOTTING 快照 ################################

儲存redis資料到磁碟: 標識N秒內key改變N次就會持久化到磁碟

save <seconds> <changes>

save "" : 空行可能會清除之前的save point資料

900s內key改變1次就持久化1次DB

save 900 1 save 300 10 save 60 10000

Redis 預設持久化方案:RDB

預設RDP快照開啟(至少1個儲存點)並且最新後臺程序儲存save point失敗,redis不會接受新寫請求

且會讓使用者知道資料不會正確持久化到磁碟,否則沒有通知會造成災難性後果

如果後臺儲存程序重新開始工作,redis會再次允許寫請求,但是如果對REDIS伺服器和持久化設定

適當的監控,即使磁碟問題、認證等等問題,仍希望redis繼續工作,可取消該功能

stop-writes-on-bgsave-error yes

dump rdb資料庫是否使用LZF演算法壓縮字串物件,節省空間

rdbcompression yes

Redis 5版本後文rdb檔案結果新增CRC64校驗碼,但儲存RDB檔案時有10%的效能損耗,提升最大效能可忽視校驗

rdbchecksum yes

dump db的檔名

dbfilename dump.rdb

Redis 工作目錄,DB會寫入該目錄的dbfilename檔案, AOF 同樣也會在該目錄建立檔案

dir ./

################################# REPLICATION 複本 #################################

使用slaveof配置Master-Slave複製

1. redis複本是非同步,出現master未連線指定slave數量可配置master停止接收寫請求

2. 若短時間內複製連線丟失(網路抖動),redis slaves可與master執行部分資料的重同步

3. 複本無需使用者干預是自動進行的,從節點會自動連線主節點並同步

slaveof <masterip> <masterport>

若master密碼保護(requirepass), 從裝置同步資料前需指定master訪問密碼,否則會被master拒絕

masterauth <master-password>

slave斷開master連線或證進行資料同步,slave以2種不同方式執行

1. slave-serve-stale-data:yes slave將舊資料返回給客戶端,或者第一次同步直接返回空

2. slave-serve-stale-data: no slave正在同步slave直接返回SYNC with master in progress錯誤資訊

slave-serve-stale-data yes

Redis配置slave工作模式:2.6版本後預設只讀,當然slave可設定接收部分臨時資料,與master rsync時會被刪掉

但未保護資料,不建議這麼操作

slave-read-only yes

Replication SYNC strategy: disk or socket.

新slave或重連的slave不同繼續僅接受差異資料的複製程序。節點需要全部同步,1個rdb檔案從master傳輸到slaves有2個方式:

1. Disk-backed: master建立新檔案到磁碟的新程序,後來未見由父程序遞增傳輸給slaves,比較可靠

2. Diskless: master伺服器建立寫rdb檔案到slave sockets的程序,不需要依賴磁碟,依賴網路

特點:slave傳輸資料預設都會放入佇列,排隊完成資料的全同步

當使用無盤複製,master在開始傳輸前會等待1段時間,用於等待多個slaves到達進行並行傳輸,及1個批次傳輸服務多個slaves

低延遲磁碟和快、大寬頻網路,diskless複製工作效果更好

repl-diskless-sync no

diskless 開啟,預設開始傳輸資料前的延時,方便更多slaves介入1個批次並行傳輸

repl-diskless-sync-delay 5

slave ping master時間間隔,檢測複製過程master、slave故障問題

repl-ping-slave-period 10

複製超時設定:> repl-ping-slave-period, 包含:資料網路超時 + master處理超時((data, pings)) + slave確認複製超時(REPLCONF ACK pings)

repl-timeout 60

Disable TCP_NODELAY on the slave socket after SYNC?

SYNC後是否禁用TCP_NODELAY

yes: 禁用,redis使用少量tcp包,更小的寬頻傳送資料到從節點,但是slave接收資料可能會增加延時,linux核心預設40ms(網路高延遲)

no: 客戶端延遲會降低,但複製需要更多寬頻(低延遲網路環境:預設) nagle演算法, 傳送資料到緩衝區達到一定程度才傳送到客戶端,充分利用網路頻寬

repl-disable-tcp-nodelay no

設定複製backlog長度,backlog累計slaves斷開積累的資料,以便slave重連上通過部分resync同步,而不需全量同步

backlog大寫與slave斷開時間成正比關係,backlog有1個slave連線時僅分配1次

repl-backlog-size 1mb

slave與master斷開最長時間,超過則釋放backlog,0標識不釋放backlog

repl-backlog-ttl 3600

slave特權是1個數字,用於master節點故障,sentinel(哨兵)提升slave為master,可通過INFO查詢

數字越小許可權越高,0 標識slave不會被sentinel選中為master,預設許可權100

slave-priority 100

限制master節點少於延遲少於10秒的3個slave連線節點,master停止接收寫請求,保證master每次多有效能高效的slave提供服務

min-slaves-to-write 3

min-slaves-max-lag 10

################################## SECURITY 安全 ###################################

Redis節點密碼配置

requirepass foobared

Command renaming.

命令重新命名:例如key * 重新命名為"",防止生產環境造成Redis奔潰

rename-command CONFIG ""

################################### LIMITS 限制 ####################################

設定同時刻最大客戶端連線數

maxclients 10000

不要使用記憶體超過redis記憶體數量,超過redis按照預期過期策略清理key: maxmemory-policy

如noeviction不使用過期策略,reids使用更多記憶體的命令(寫、修改操作)直接返回Error,只讀則正常執行

節點最大使用記憶體

maxmemory <bytes>

MAXMEMORY POLICY: 記憶體達到最大值,Redis如何清除資料

5種資料清除策略:

volatile-lru -> LRU演算法清除存在有key

allkeys-lru -> LRU清除任何key

volatile-random -> 隨機清除存在有效期的

allkeys-random -> 隨機清除key

volatile-ttl -> 清除最近快過期的key: 不是精確演算法,但是最合適的演算法

noeviction -> 不清除key,寫操作報錯(預設策略)

注意:如果沒有適合的key清除,redis對任何策略都會報錯返回

寫操作:set setnx setex append

incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd

sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby

zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby

getset mset msetnx exec sort

The default is:

maxmemory-policy noeviction

LRU演算法淘汰策略:預設從最近沒用的5個key裡面選1個淘汰,10個接近於LRU但消耗更多CPU,3個不是很精確

maxmemory-samples 5

############################## APPEND ONLY MODE 追加模式AOF###############################

預設redis非同步dump資料集(rdb)到磁碟,該模式可能會造成快取幾分鐘的寫資料丟失,因主節點故障快照還未即時匯出,期間的資料丟失

AOF是提供更好持久化的模式,例如預設fsync策略,伺服器斷電或者redis程序自身錯誤,redis僅僅丟失1s寫的資料

AOF和RDP持久化可同時進行,Redis開啟,redis將從AOF載入資料,因AOF擁有更好的持久化保障

開始AOF模式

appendonly yes

工作空間AOF檔名

appendfilename "appendonly.aof"

fsymc()函式通知OS將資料寫入磁碟,而不是更待更多資料進入輸出快取

redis支援3種不同模式:

1. no: don't fsync:OS按自身排程持久化資料,一般OS 30s重新整理一次資料

2. always: 每次redis寫請求追加到AOF 日誌檔案,速度慢但最安全

3. erverysec: 折中方案,每秒重新整理資料到磁碟(預設)

appendfsync everysec

AOF fsync policy設定為always或everysec,後臺儲存程序會執行很多IO操作,一些Linux

配置redis可能會阻塞大量的fsync呼叫,當前是沒辦法解決的,緩解方法是儘管BGSAVE、BGREWRITEAOF

在執行,組織fsync在主程序中呼叫,類似於appendfsync none效果,最壞的情況是30s資料丟失

如果有上述問題則設定yes,否則設定no

no-appendfsync-on-rewrite no

redis資料增長到指定比例,可自動呼叫BGREWRITEAOF重寫AOF日誌檔案

工作流程:redis記住最新重寫的檔案大小,如果沒有則以啟動時的AOP為準,基準日志大小與

當前日誌檔案大小比較,如果當前大小大於指定比例,自動觸發重寫操作。同樣也要指定重寫AOF檔案

的最小大小,否則可能出現比例達到但檔案很小的情況

當前檔案達到基準路徑的2倍則觸發重寫操作

auto-aof-rewrite-percentage 200 auto-aof-rewrite-min-size 64mb

當Redis啟動時AOF重新匯入記憶體,可能最後會出現截斷的資料,當redis執行的OS

崩潰,ext4檔案系統沒有data=ordered選項導致的,但是os正常,redis崩潰不會

造成資料截斷,當這個問題出現時Redis可以退出或儘可能載入(預設機制)

aof-load-truncated yes: redis會發送日誌資訊給事件使用者

aof-load-truncated no: 伺服器因為錯誤終止,拒絕啟動。設定no要求使用者使用redis-check-aof

手動修改AOF檔案,然後再重啟redis伺服器

注意:AOF檔案中間錯誤,伺服器會因為錯誤退出,該選項適用於儘可能從AOF讀更多的資料,

而不是適用於沒有找到足夠的AOF資料

aof-load-truncated yes

################################ LUA SCRIPTING LUA指令碼 ###############################

Lua指令碼最長執行時間,單位毫秒,如果執行時間達到最長執行約束,redis記錄指令碼正在執行,但是

對redis執行操作返回error,因為redis是單執行緒,每次只允許1個指令執行,lua指令碼具有原子性,

相當於聚合命令,這期間僅僅SCRIPT KILL和SHUTDOWN NOSAVE命令可用,SCRIPT KILL用於停止

還沒被寫命令呼叫的指令碼,SHUTDOWN NOSAVE 唯一一種方式關閉伺服器以防指令碼執行報錯,使用者

不想等指令碼自然完成終止,造成redis服務不可用

0或復值表示不記錄指令碼最長事件,不會輸出警告日誌資訊

lua-time-limit 5000

################################ REDIS CLUSTER 叢集 ###############################

開啟redis叢集

cluster-enabled yes

redis cluster 節點配置檔案,不推薦手工更改,由節點自動更新

cluster-config-file nodes-6379.conf

redis 叢集節點失去聯絡最長時間認定為失敗,會被踢出redis cluster(毫秒)

cluster-node-timeout 15000

若資料過期,故障master節點的slave避免開始故障轉移,檢測機制:

1. 多個slave可故障轉移,檢測最新的複本偏移量(資料量)排名

2. 每個slave計算最後一次與master的通訊時間,可能是ping\connected等時間,老時間不進行故障轉移

可手動指定slave不進行故障轉移

規則:> (node-timeout * slave-validity-factor) + repl-ping-slave-period

cluster-slave-validity-factor 10

Default is 1 (slaves migrate only if their masters remain with at least

one slave). To disable migration just set it to a very large value.

A value of 0 can be set but is useful only for debugging and dangerous

in production.

只有其他主節點還有富餘的slave節點,才會分配主節點給叢集獨立的主節點

cluster-migration-barrier 1

預設叢集檢測至少1個hash slot故障,redis停止服務,但是某些情況為了儘可能提供伺服器,已暴露

的slot仍可提供自身key space的key操作,則設定no

cluster-require-full-coverage yes

In order to setup your cluster make sure to read the documentation

available at http://redis.io web site.

################################## SLOW LOG ###################################

Redis Slow Log 是一個記錄超過指定時間的日誌查詢系統,執行時間不包含IO操作(主要客戶端通訊),

僅僅包含時間命令實際執行時間

引數:

1. 設定redis命令執行時間:微秒

2. slow log長度,新命令記錄時就記錄會從記錄的命令佇列刪除

設定執行命令的時間(微秒),超過則記錄,負數禁用slow log,0則強制記錄每個命令

slowlog-log-slower-than 10000

自定義日誌長度,可通過SLOWLOG RESET重新宣告

slowlog-max-len 128

################################ LATENCY MONITOR 延遲監控 ##############################

Redis監控子系統在執行時取樣不同的操作,為了收集相關資料,LATENCY命令可用於列印圖形和獲取報告

系統只會記錄指定時間>=latency-monitor-threshold的操作,0標識關閉延遲監控,預設監控廣播

redis執行中手動開啟監控命令:CONFIG SET latency-monitor-threshold <milliseconds>

latency-monitor-threshold 0

############################# EVENT NOTIFICATION 事件通知 ##############################

Redis可通知Pub/Sub客戶端相關事件

例如:刪除db0中的key foo,將會發送2條資訊,一般可用於分佈鎖通知,監控鎖節點事件

PUBLISH keyspace@0:foo del

PUBLISH keyevent@0:del foo

Redis支援事件種類:支援簡寫字元

K Keyspace events, published with keyspace@<db> prefix. key空間命令: 具體key操作

E Keyevent events, published with keyevent@<db> prefix. key事件:受影響的key

g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... key操作命令

$ String commands 字串命令

l List commands set命令

s Set commands 排序資料命令

h Hash commands hash命令

z Sorted set commands 排序set命令

x Expired events (events generated every time a key expires) 過期事件

e Evicted events (events generated when a key is evicted for maxmemory)

A Alias for g$lshzxe, so that the "AKE" string means all the events.

"notify-keyspace-events":引數0-N個字元,控制符標識禁用notify-keyspace-events事件

例如:E:K事件通知 l: list命令 g:通用命令

notify-keyspace-events Elg

為節省資源,預設為空難,基礎配置:EK(監聽key操作及受影響的key)

notify-keyspace-events ""

############################### ADVANCED CONFIG 高階配置 ###############################

面對少量實體或最大實體值未超過指定限制,雜湊是1個高效的資料結構,滿足條件特殊優化

hash-max-ziplist-entries 512 hash-max-ziplist-value 64

類似hash,少量陣列成員,成員最大值不超過限制則特殊優化

list-max-ziplist-entries 512 list-max-ziplist-value 64

set優化唯一場景:set成員都是字串,且在64位有符號整數範圍,在指定成員數量範圍內優化

set-max-intset-entries 512

zset優化:zset成員數少於指定數量,最大成員不大於指定值,set本質特殊的hash

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

HyperLogLog sparse representation bytes limit. The limit includes the

16 bytes header. When an HyperLogLog using the sparse representation crosses

this limit, it is converted into the dense representation.

A value greater than 16000 is totally useless, since at that point the

dense representation is more memory efficient.

The suggested value is ~ 3000 in order to have the benefits of

the space efficient encoding without slowing down too much PFADD,

which is O(N) with the sparse encoding. The value can be raised to

~ 10000 when CPU is not a concern, but space is, and the data set is

composed of many HyperLogLogs with cardinality in the 0 - 15000 range.

hll-sparse-max-bytes 3000

Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in

order to help rehashing the main Redis hash table (the one mapping top-level

keys to values). The hash table implementation Redis uses (see dict.c)

performs a lazy rehashing: the more operation you run into a hash table

that is rehashing, the more rehashing "steps" are performed, so if the

server is idle the rehashing is never complete and some more memory is used

by the hash table.

The default is to use this millisecond 10 times every second in order to

actively rehash the main dictionaries, freeing memory when possible.

If unsure:

use "activerehashing no" if you have hard latency requirements and it is

not a good thing in your environment that Redis can reply from time to time

to queries with 2 milliseconds delay.

use "activerehashing yes" if you don't have such hard requirements but

want to free memory asap when possible.

activerehashing yes

The client output buffer limits can be used to force disconnection of clients

that are not reading data from the server fast enough for some reason (a

common reason is that a Pub/Sub client can't consume messages as fast as the

publisher can produce them).

The limit can be set differently for the three different classes of clients:

normal -> normal clients including MONITOR clients

slave -> slave clients

pubsub -> clients subscribed to at least one pubsub channel or pattern

The syntax of every client-output-buffer-limit directive is the following:

client-output-buffer-limit <class> <hard limit> <soft limit> <soft seconds>

A client is immediately disconnected once the hard limit is reached, or if

the soft limit is reached and remains reached for the specified number of

seconds (continuously).

So for instance if the hard limit is 32 megabytes and the soft limit is

16 megabytes / 10 seconds, the client will get disconnected immediately

if the size of the output buffers reach 32 megabytes, but will also get

disconnected if the client reaches 16 megabytes and continuously overcomes

the limit for 10 seconds.

By default normal clients are not limited because they don't receive data

without asking (in a push way), but just after a request, so only

asynchronous clients may create a scenario where data is requested faster

than it can read.

Instead there is a default limit for pubsub and slave clients, since

subscribers and slaves receive data in a push fashion.

Both the hard or the soft limit can be disabled by setting them to zero.

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

Redis calls an internal function to perform many background tasks, like

closing connections of clients in timeot, purging expired keys that are

never requested, and so forth.

Not all tasks are perforemd with the same frequency, but Redis checks for

tasks to perform according to the specified "hz" value.

By default "hz" is set to 10. Raising the value will use more CPU when

Redis is idle, but at the same time will make Redis more responsive when

there are many keys expiring at the same time, and timeouts may be

handled with more precision.

The range is between 1 and 500, however a value over 100 is usually not

a good idea. Most users should use the default of 10 and raise this up to

100 only in environments where very low latency is required.

hz 10

當子程序重寫AOF檔案,開啟選項可生成每個32M AOF檔案則進入fsync-ed狀態,遞增提交到磁碟,避免大的延遲

aof-rewrite-incremental-fsync yes

################################## INCLUDES 引用配置 ###################################

Include one or more other config files here. This is useful if you

have a standard template that goes to all Redis server but also need

to customize a few per-server settings. Include files can include

other files, so use this wisely.

自引用配置檔案,例如伺服器叢集公共配置抽取出來,只需維護1個配置檔案版本,每個節點在各自

補充自有伺服器配置,類似jquery的extend函式

include /path/to/local.conf

include