1. 程式人生 > >Redis 配置節

Redis 配置節

Redis

後面的配置基於4.0.9版本=>>>不指定版本資訊的配置說明都是耍流氓

比如在4.0.9中沒有vm相關的及glueoutputbuf的配置資訊

部分常用配置節(後面有詳細說明):

  • daemonize
  • pidfile
  • port
  • bind
  • timeout
  • loglevel
  • logfile
  • databases
  • save
  • rdbcompression
  • dbfilename
  • dir
  • slaveof
  • masterauth
  • requirepass
  • maxclients
  • maxmemory
  • maxmemory-policy
  • appendonly
  • appendfilename
  • appendfsync
  • hash-max-zipmap-entries
  • hash-max-zipmap-value
  • activerehashing
  • include

Redis介紹

開源記憶體資料庫,支援String、Hash、List、Set、Zset、Geo、Hyperloglogs等多資料結構。同事支援主從複製、Luau指令碼、事務、資料持久化、高可用和叢集化等;

Redis特性

  1. 高效能:Redis雖然是單執行緒的,但是它同樣擁有這超高的效能。有測試顯示每秒請求OPS能夠達到10W左右;
  2. 多樣化資料結構:Redis支援String、Hash、List、Set、Zset、Geo等多資料結構;
  3. 持久化:
    1. RDB持久化(快照式持久化方式),將記憶體中的全量資料dump到磁碟。它的優勢是載入速度比AOF快,劣勢是快照式的全量備份,沒有增量資料,造成資料丟失;
    2. AOF持久化:AOF記錄Redis執行的所有寫操作命令。恢復資料的過程相當於回放這些寫操作。使用AOF的持久化方式,優勢是有靈活的刷盤策略,保證資料的安全性。劣勢是AOF檔案體積比RDB大,佔用磁碟多,資料載入到記憶體的速度慢;
  4. 多重資料刪除策略:
    1. 惰性刪除:當讀/寫一個已經過期的key時,會觸發惰性刪除策略,刪除掉這個過期key;
    2. 定期刪除:由於惰性刪除策略無法保證冷資料被及時刪掉,所有redis會定期主動淘汰一批已過期的key;
    3. 主動刪除:當已用記憶體超過maxmemory限定時,觸發主動清除策略,該策略由啟動引數的配置決定,可配置引數及說明如下:
      • volatile-lru:從已設定過期時間的樣本中根據LRU演算法刪除資料 (redis3.0之前的預設策略)
      • volatile-ttl:從已設定過期時間的樣本中挑選過期時間最小的資料刪除
      • volatile-random:從已設定過期時間的樣本中隨機選擇資料刪除
      • allkeys-lru:從樣本中根據LRU演算法刪除資料
      • allkeys-random:從樣本中任意選擇刪除資料
      • noenviction:禁止從記憶體中刪除資料 (從redis3.0 開始預設策略)
  5. 高可用:Redis自身帶有哨兵(Sentinel)的元件,可以監控Redis主從的執行轉態和自動的故障切換,實現Redis的高可用;

Redis安裝配置

Redis安裝

1.Redis下載並解壓(目前最新版本是4.0.9)

cd /usr/local/
wget http://download.redis.io/releases/redis-4.0.9.tar.gz
tar -zxzf redis-4.0.9.tar.gz

2.編譯並安裝

make install PREFIX=安裝路徑

cd /usr/local/redis-4.0.9
make install PREFIX=/usr/local/redis

可以複製redis相關命令到/usr/sbin目錄下,這樣就可以執行執行這些命令,不用謝全路徑

cd /usr/local/redis/bin
cp redis-cli redis-server redis-sentinel /usr/sbin

3.Redis配置(v4.0.9)

redis的配置檔案(redis.conf)拷貝備份

個人習慣,喜歡把最原始的配置檔案做一個備份,便於後期對比或還原

redis配置檔案主要引數解析參考

  • daemonize

配置Redis是否以守護程序的方式執行,預設為no

# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize no
  • pidfile

當Redis以守護程序方式執行時,Redis預設會把pid寫入/var/run/redis.pid檔案,可以通過pidfile指定

# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
# Creating a pid file is best effort: if Redis is not able to create it
# nothing bad happens, the server will start and run normally.
pidfile /var/run/redis_6379.pid
  • port

指定Redis的監聽埠,埠預設6379(來源一個女歌手的名字)

# Accept connections on the specified port, default is 6379 (IANA #815344).
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379
  • bind

繫結的主機地址

# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 lookback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bind 127.0.0.1
  • timeout

當客戶端閒置多長時間後關閉連線,如果指定為0,表示關閉該功能

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0
  • loglevel

指定日誌記錄級別,Redis共支援4個級別:debug、verbose、notice、warning,預設為notice

# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice
  • logfile

日誌記錄方式,預設為標準輸出,如果配置Redis為守護程序方式執行,而這裡又配置為日誌記錄方式為標準輸出,則將日誌傳送給/dev/null

# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile ""
  • databases

設定資料庫的數量,預設資料庫為0,可以使用SELECT <dbid> 命令在連線上指定資料庫id

# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16
  • save

指定在多長時間內,有多少次更新操作,就將資料同步到資料檔案,可以多個條件配合

預設的

# Save the DB on disk:
#
#   save <seconds> <changes>
#
#   Will save the DB if both the given number of seconds and the given
#   number of write operations against the DB occurred.
#
#   In the example below the behaviour will be to save:
#   after 900 sec (15 min) if at least 1 key changed
#   after 300 sec (5 min) if at least 10 keys changed
#   after 60 sec if at least 10000 keys changed
#
#   Note: you can disable saving completely by commenting out all "save" lines.
#
#   It is also possible to remove all the previously configured save
#   points by adding a save directive with a single empty string argument
#   like in the following example:
#
#   save ""

save 900 1
save 300 10
save 60 10000
  • rdbcompression

指定儲存至本地資料庫時是否壓縮資料,預設為yes,Redis採用LZF(Apache開源演算法)壓縮,如果為了節省CPU時間,可以關閉該選項,但會導致資料庫檔案變的巨大

# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes
  • dbfilename

指定本地資料庫檔名,預設為dump.rdb

# The filename where to dump the DB
dbfilename dump.rdb
  • dir

指定本地資料庫存放目錄

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir ./
  • slaveof

設定當本機為slave服務時,設定master服務的ip地址及埠,Redis啟動時,會自動從master進行資料同步

# Master-Slave replication. Use slaveof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# 1) Redis replication is asynchronous, but you can configure a master to
#    stop accepting writes if it appears to be not connected with at least
#    a given number of slaves.
# 2) Redis slaves are able to perform a partial resynchronization with the
#    master if the replication link is lost for a relatively small amount of
#    time. You may want to configure the replication backlog size (see the next
#    sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
#    network partition slaves automatically try to reconnect to masters
#    and resynchronize with them.
#
# slaveof <masterip> <masterport>
  • masterauth

當master服務設定了密碼保護時,salve服務連線master的密碼

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the slave to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the slave request.
#
# masterauth <master-password>
  • requirepass

設定Redis的連線密碼,如果配置了連線密碼,客戶端在連線Redis時,需要通過AUTH <password>命令提供密碼,預設關閉

# Require clients to issue AUTH <PASSWORD> before processing any other
# commands.  This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
# requirepass foobared
  • maxclients

設定同一時間最大客戶端連線數,預設無限制,Redis可以同時開啟的客戶端連線數為Redis程序可以開啟的最大描述檔案符數,如果設定maxclients 0,表示不限制。當客戶端連線數達到限制時,Redis會關閉新的連線,並想客戶端返回max number of clients reached錯誤資訊

# Set the max number of connected clients at the same time. By default
# this limit is set to 10000 clients, however if the Redis server is not
# able to configure the process file limit to allow for the specified limit
# the max number of allowed clients is set to the current file limit
# minus 32 (as Redis reserves a few file descriptors for internal uses).
#
# Once the limit is reached Redis will close all the new connections sending
# an error 'max number of clients reached'.
#
# maxclients 10000
  • maxmemory

指定Redis最大記憶體限制,Redis在啟動時會把資料載入到記憶體中,達到最大記憶體後,Redis將會無法再進行寫入操作,但任然可以進行讀取操作。記憶體清理使用下面的記憶體清理策略進行。Redis新的vm機制,會把Key存放記憶體,Value存放在swap區

# Set a memory usage limit to the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected (see maxmemory-policy).
#
# If Redis can't remove keys according to the policy, or if the policy is
# set to 'noeviction', Redis will start to reply with errors to commands
# that would use more memory, like SET, LPUSH, and so on, and will continue
# to reply to read-only commands like GET.
#
# This option is usually useful when using Redis as an LRU or LFU cache, or to
# set a hard memory limit for an instance (using the 'noeviction' policy).
#
# WARNING: If you have slaves attached to an instance with maxmemory on,
# the size of the output buffers needed to feed the slaves are subtracted
# from the used memory count, so that network problems / resyncs will
# not trigger a loop where keys are evicted, and in turn the output
# buffer of slaves is full with DELs of keys evicted triggering the deletion
# of more keys, and so forth until the database is completely emptied.
#
# In short... if you have slaves attached it is suggested that you set a lower
# limit for maxmemory so that there is some free RAM on the system for slave
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory <bytes>
  • maxmemory-policy

記憶體達到設定的最大記憶體後,將要使用哪種策略進行記憶體清理

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones with 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.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
# Note: with any of the above policies, Redis will return an error on write
#       operations, when there are no suitable keys for eviction.
#
#       At the date of writing these commands are: 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
  • appendonly

指定是否在每次更新操作後進行日誌記錄,Redis預設情況下是非同步的把資料寫入磁碟,如果不開啟,可能會在斷電時導致一段時間內的資料丟失。因為Redis本身同步資料檔案是按上面save條件來同步的,所以有的資料會在一段時間內只存在於記憶體中。預設為no

# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.

appendonly no
  • appendfilename

指定更新日誌檔名

# The name of the append only file (default: "appendonly.aof")

appendfilename "appendonly.aof"
  • appendfsync

指定更新日誌條件,共有3個可選值

# The fsync() call tells the Operating System to actually write data on disk
# instead of waiting for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log. Slow, Safest.
# everysec: fsync only one time every second. Compromise.
#
# The default is "everysec", as that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# More details please check the following article:
# http://antirez.com/post/redis-persistence-demystified.html
#
# If unsure, use "everysec".

# appendfsync always
appendfsync everysec
# appendfsync no
  • hash-max-zipmap-entrieshash-max-zipmap-value

指定在超過一定的數量或者最大的元素超過某個臨界值時,採用一種特殊的雜湊演算法

# Hashes are encoded using a memory efficient data structure when they have a
# small number of entries, and the biggest entry does not exceed a given
# threshold. These thresholds can be configured using the following directives.
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
  • activerehashing

指定是否啟用重置雜湊,預設為開啟

# 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
  • include

指定包含其它的配置檔案,可以在同一個主機上多個Redis例項之間使用同一份配置檔案,而同時各個例項又擁有自己的特定配置檔案

# Include one or more other config files here.  This is useful if you
# have a standard template that goes to all Redis servers but also need
# to customize a few per-server settings.  Include files can include
# other files, so use this wisely.
#
# Notice option "include" won't be rewritten by command "CONFIG REWRITE"
# from admin or Redis Sentinel. Since Redis always uses the last processed
# line as value of a configuration directive, you'd better put includes
# at the beginning of this file to avoid overwriting config change at runtime.
#
# If instead you are interested in using includes to override configuration
# options, it is better to use include as the last line.
#
# include /path/to/local.conf
# include /path/to/other.conf