概述
Redis 的配置文件放置在其安装目录下,如果是 Windows 系统,则默认的配置文件就是 redis .window.conf 如果是 Linux 系统,则是 redis.conf。在大部分的情况下我们都使用到Linux 环境,这里我们以linux环境为例。
Redis CONFIG 命令
可以通过 CONFIG 命令查看或设置配置项,临时生效。重启后失效。
CONFIG GET
redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
比如
127.0.0.1:6379> CONFIG GET requirepass 1) "requirepass" 2) "artisan" 127.0.0.1:6379> CONFIG GET bind 1) "bind" 2) "" 127.0.0.1:6379> CONFIG GET loglevel 1) "loglevel" 2) "notice" 127.0.0.1:6379>
使用 * 号获取所有配置项
127.0.0.1:6379> CONFIG GET * 1) "dbfilename" 2) "dump.rdb" 3) "requirepass" 4) "artisan" 5) "masterauth" 6) "" 7) "cluster-announce-ip" 8) "" 9) "unixsocket" 10) "" 11) "logfile" 12) "" 13) "pidfile" 14) "/var/run/redis_6379.pid" 15) "slave-announce-ip" 16) "" 17) "maxmemory" 18) "0" 19) "proto-max-bulk-len" 20) "536870912" 21) "client-query-buffer-limit" 22) "1073741824" 23) "maxmemory-samples" 24) "5" 25) "lfu-log-factor" 26) "10" 27) "lfu-decay-time" 28) "1" 29) "timeout" 30) "0" 31) "active-defrag-threshold-lower" 32) "10" 33) "active-defrag-threshold-upper" 34) "100" 35) "active-defrag-ignore-bytes" 36) "104857600" 37) "active-defrag-cycle-min" 38) "25" 39) "active-defrag-cycle-max" 40) "75" 41) "auto-aof-rewrite-percentage" 42) "100" 43) "auto-aof-rewrite-min-size" 44) "67108864" 45) "hash-max-ziplist-entries" 46) "512" 47) "hash-max-ziplist-value" 48) "64" 49) "list-max-ziplist-size" 50) "-2" 51) "list-compress-depth" 52) "0" 53) "set-max-intset-entries" 54) "512" 55) "zset-max-ziplist-entries" 56) "128" 57) "zset-max-ziplist-value" 58) "64" 59) "hll-sparse-max-bytes" 60) "3000" 61) "lua-time-limit" 62) "5000" 63) "slowlog-log-slower-than" 64) "10000" 65) "latency-monitor-threshold" 66) "0" 67) "slowlog-max-len" 68) "128" 69) "port" 70) "6379" 71) "cluster-announce-port" 72) "0" 73) "cluster-announce-bus-port" 74) "0" 75) "tcp-backlog" 76) "511" 77) "databases" 78) "16" 79) "repl-ping-slave-period" 80) "10" 81) "repl-timeout" 82) "60" 83) "repl-backlog-size" 84) "1048576" 85) "repl-backlog-ttl" 86) "3600" 87) "maxclients" 88) "4064" 89) "watchdog-period" 90) "0" 91) "slave-priority" 92) "100" 93) "slave-announce-port" 94) "0" 95) "min-slaves-to-write" 96) "0" 97) "min-slaves-max-lag" 98) "10" 99) "hz" 100) "10" 101) "cluster-node-timeout" 102) "15000" 103) "cluster-migration-barrier" 104) "1" 105) "cluster-slave-validity-factor" 106) "10" 107) "repl-diskless-sync-delay" 108) "5" 109) "tcp-keepalive" 110) "300" 111) "cluster-require-full-coverage" 112) "yes" 113) "cluster-slave-no-failover" 114) "no" 115) "no-appendfsync-on-rewrite" 116) "no" 117) "slave-serve-stale-data" 118) "yes" 119) "slave-read-only" 120) "yes" 121) "stop-writes-on-bgsave-error" 122) "yes" 123) "daemonize" 124) "yes" 125) "rdbcompression" 126) "yes" 127) "rdbchecksum" 128) "yes" 129) "activerehashing" 130) "yes" 131) "activedefrag" 132) "no" 133) "protected-mode" 134) "yes" 135) "repl-disable-tcp-nodelay" 136) "no" 137) "repl-diskless-sync" 138) "no" 139) "aof-rewrite-incremental-fsync" 140) "yes" 141) "aof-load-truncated" 142) "yes" 143) "aof-use-rdb-preamble" 144) "no" 145) "lazyfree-lazy-eviction" 146) "no" 147) "lazyfree-lazy-expire" 148) "no" 149) "lazyfree-lazy-server-del" 150) "no" 151) "slave-lazy-flush" 152) "no" 153) "maxmemory-policy" 154) "noeviction" 155) "loglevel" 156) "notice" 157) "supervised" 158) "no" 159) "appendfsync" 160) "everysec" 161) "syslog-facility" 162) "local0" 163) "appendonly" 164) "no" 165) "dir" 166) "/home/redis/redis" 167) "save" 168) "900 1 300 10 60 10000" 169) "client-output-buffer-limit" 170) "normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60" 171) "unixsocketperm" 172) "0" 173) "slaveof" 174) "" 175) "notify-keyspace-events" 176) "" 177) "bind" 178) "" 127.0.0.1:6379>
CONFIG SET
可以通过修改 redis.conf 文件或使用 CONFIG set 命令来修改配置。
语法
redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
举例
127.0.0.1:6379> CONFIG SET loglevel "notice" OK 127.0.0.1:6379>
Redis redis.conf文件
部分配置项说明
daemonize
# 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.
Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程
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
当Redis以守护进程方式运行,如果没有创建成功,看看是不是在/var/run没有创建文件的权限 . 前提 daemonize yes
[redis@artisan bin]$ ./redis-cli 127.0.0.1:6379> auth artisan OK 127.0.0.1:6379> CONFIG GET pidfile 1) "pidfile" 2) "/var/run/redis_6379.pid" 127.0.0.1:6379>
port
# 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
指定redis监听端口
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
# Close the connection after a client is idle for N seconds (0 to disable) timeout 0
当 客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
loglevel
# 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
指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认为verbose
logfile
# 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 ""
指定日志文件位置.,默认为标准输出,如果配置Redis为守护进程方式运行,而这里又配置为日志记录方式为标准输出,则日志将会发送给/dev/null
database
# 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
设置数据库的数量,默认数据库为0,可以使用SELECT <dbid>
命令在连接上指定数据库id
save
################################ SNAPSHOTTING ################################ # # 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
指定在多长时间内,有多少次更新操作,就将数据同步到数据文件,可以多个条件配合.
Redis默认配置文件中提供了三个条件:
save 900 1 save 300 10 save 60 10000
分别表示900秒(15分钟)内有1个更改,300秒(5分钟)内有10个更改以及60秒内有10000个更改。
rdbcompression
# 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
指定存储至本地数据库时是否压缩数据,默认为yes,Redis采用LZF压缩,如果为了节省CPU时间,可以关闭该选项,但会导致数据库文件变的巨大
dbfilename
# The filename where to dump the DB dbfilename dump.rd
指定本地数据库文件名,默认值为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
# 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>
设置当本机为slave服务时,设置master服务的IP地址及端口,在Redis启动时,它会自动从master进行数据同步。 即 本机若为salve时,设置master的IP地址和端口,当redis启动时会自动从master进行数据同步。
masterauth
# 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>
当master服务设置了密码保护时,slave服务连接master的密码
requirepass
# 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 artisan
设置Redis连接密码,如果配置了连接密码,客户端在连接Redis时需要通过AUTH <password>
命令提供密码,默认关闭
maxclients
# 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
设置同一时间最大客户端连接数,默认无限制,Redis可以同时打开的客户端连接数为Redis进程可以打开的最大文件描述符数,如果设置 maxclients 0,表示不作限制。当客户端连接数到达限制时,Redis会关闭新的连接并向客户端返回max number of clients reached错误信息
maxmemory
# 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>
指定Redis最大内存限制,Redis在启动时会把数据加载到内存中,达到最大内存后,Redis会先尝试清除已到期或即将到期的Key,当此方法处理 后,仍然到达最大内存设置,将无法再进行写入操作,但仍然可以进行读取操作。Redis新的vm机制,会把Key存放内存,Value会存放在swap区
appendonly
# 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
指定是否在每次更新操作后进行日志记录,Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一段时间内的数据丢失。因为 redis本身同步数据文件是按上面save条件来同步的,所以有的数据会在一段时间内只存在于内存中。默认为no
appendfilename
# The name of the append only file (default: "appendonly.aof") appendfilename "appendonly.aof"
指定更新日志文件名,默认为appendonly.aof
appendfsync
# 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
指定更新日志条件,共有3个可选值:
- no:表示等操作系统进行数据缓存同步到磁盘(快)
- always:表示每次更新操作后手动调用fsync()将数据写到磁盘(慢,安全)
- everysec:表示每秒同步一次(折衷,默认值)
include
# 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
指定包含其它的配置文件,可以在同一主机上多个Redis实例之间使用同一份配置文件,而同时各个实例又拥有自己的特定配置文件
protected-mode
# Protected mode is a layer of security protection, in order to avoid that # Redis instances left open on the internet are accessed and exploited. # # When protected mode is on and if: # # 1) The server is not binding explicitly to a set of addresses using the # "bind" directive. # 2) No password is configured. # # The server only accepts connections from clients connecting from the # IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain # sockets. # # By default protected mode is enabled. You should disable it only if # you are sure you want clients from other hosts to connect to Redis # even if no authentication is configured, nor a specific set of interfaces # are explicitly listed using the "bind" directive. protected-mode yes
当安全模式启用时
- 1)服务器没有配置bind
- 2)没有配置密码
则服务器默认只接受本地的连接和 Unix domain sockets
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
最大内存策略:如果达到内存限制,Redis如何选择删除key
可以在以下五个选项里选择:
volatile-lru -> 根据LRU算法生成的过期时间来删除。
allkeys-lru -> 根据LRU算法删除任何key。
volatile-random -> 根据过期设置来随机删除key。
allkeys->random -> 无差别随机删。
volatile-ttl -> 根据最近过期时间来删除(辅以TTL)
noeviction -> 谁也不删,直接在写操作时返回错误。
注意:对所有策略来说,如果Redis找不到合适的可以删除的key都会在写操作的时候返回一个错误。
目前涉及的命令有: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
默认值为:maxmemory-policy noeviction