美文网首页
redis配置文件redis.conf参数说明

redis配置文件redis.conf参数说明

作者: 羁绊_87cd | 来源:发表于2020-06-10 14:02 被阅读0次
    # 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启用守护进程
    daemonize no
    
    # When running daemonized, Redis writes a pid file in /var/run/redis.pid by
    # default. You can specify a custom pid file location here.
    #当 Redis 以守护进程的方式运行的时候,Redis 默认会把 pid 文件放在/var/run/redis.pid
    #可配置到其他地址,当运行多个 redis 服务时,需要指定不同的 pid 文件和端口
    pidfile /var/run/redis.pid
    
    # Accept connections on the specified port, default is 6379.
    # If port 0 is specified Redis will not listen on a TCP socket.
    #端口
    port 6379
    
    # If you want you can bind a single interface, if the bind option is not
    # specified all the interfaces will listen for incoming connections.
    #指定Redis可接收请求的IP地址,不设置将处理所有请求,建议生产环境中设置
    # bind 127.0.0.1
    
    # Close the connection after a client is idle for N seconds (0 to disable)
    #客户端连接的超时时间,单位为秒,超时后会关闭连接
    timeout 0
    
    # Set server verbosity to 'debug'
    # it 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)
    #日志记录等级,4个可选值
    loglevel notice
    
    # Specify the log file name. Also 'stdout' 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
    #配置 log 文件地址,默认打印在命令行终端的窗口上,也可设为/dev/null屏蔽日志、
    logfile stdout
    
    # Set the number of databases. The default database is DB 0, you can select
    # a different one on a per-connection basis using SELECT where
    # dbid is a number between 0 and 'databases'-1
    #设置数据库的个数,可以使用 SELECT 命令来切换数据库。
    databases 16
    
    #
    # Save the DB on disk:
    #
    #   save
    #
    #   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 at all commenting all the "save" lines.
    #设置 Redis 进行数据库镜像的频率。保存数据到disk的策略
    #900秒之内有1个keys发生变化时
    #30秒之内有10个keys发生变化时
    #60秒之内有10000个keys发生变化时
    save 900 1
    save 300 10
    save 60 10000
    
    # 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
    
    # The filename where to dump the DB
    #镜像备份文件的文件名
    dbfilename dump.rdb
    
    # The working directory.
    #
    # The DB will be written inside this directory, with the filename specified
    # above using the 'dbfilename' configuration directive.
    # 
    # Also the Append Only File will be created inside this directory.
    # 
    # Note that you must specify a directory here, not a file name.
    #数据库镜像备份的文件放置的路径
    #路径跟文件名分开配置是因为 Redis 备份时,先会将当前数据库的状态写入到一个临时文件
    #等备份完成时,再把该临时文件替换为上面所指定的文件
    #而临时文件和上面所配置的备份文件都会放在这个指定的路径当中
    #默认值为 ./
    dir /var/lib/redis/
    
    # Master-Slave replication. Use slaveof to make a Redis instance a copy of
    # another Redis server. Note that the configuration is local to the slave
    # so for example it is possible to configure the slave to save the DB with a
    # different interval, or to listen to another port, and so on.
    #设置该数据库为其他数据库的从数据库
    #slaveof <masterip> <masterport> 当本机为从服务时,设置主服务的IP及端口
    # slaveof
    
    # 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> 当本机为从服务时,设置主服务的连接密码
    # masterauth
    
    # When a slave lost the connection with the master, or when the replication
    # is still in progress, the slave can act in two different ways:
    #
    # 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will
    #    still reply to client requests, possibly with out of data data, or the
    #    data set may just be empty if this is the first synchronization.
    #
    # 2) if slave-serve-stale data is set to 'no' the slave will reply with
    #    an error "SYNC with master in progress" to all the kind of commands
    #    but to INFO and SLAVEOF.
    #当slave丢失与master的连接时,或slave仍然在于master进行数据同步时(未与master保持一致)
    #slave可有两种方式来响应客户端请求:
    #1)如果 slave-serve-stale-data 设置成 'yes'(默认),slave仍会响应客户端请求,此时可能会有问题
    #2)如果 slave-serve-stale-data 设置成 'no',slave会返回"SYNC with master in progress"错误信息,但 INFO 和SLAVEOF命令除外。
    slave-serve-stale-data yes
    
    # Require clients to issue AUTH 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.
    #设置客户端连接后进行任何其他指定前需要使用的密码
    #redis速度相当快,一个外部用户在一秒钟进行150K次密码尝试,需指定强大的密码来防止暴力破解
    # requirepass foobared
    
    # Set the max number of connected clients at the same time. By default there
    # is no limit, and it's up to the number of file descriptors the Redis process
    # is able to open. The special value '0' means no limits.
    # Once the limit is reached Redis will close all the new connections sending
    # an error 'max number of clients reached'.
    #限制同时连接的客户数量。
    #当连接数超过这个值时,redis 将不再接收其他连接请求,客户端尝试连接时将收到 error 信息
    # maxclients 128
    
    # Don't use more memory than the specified amount of bytes.
    # When the memory limit is reached Redis will try to remove keys
    # accordingly to the eviction policy selected (see maxmemmory-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 cache, or to set
    # an 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').
    #设置redis能够使用的最大内存。
    #达到最大内存设置后,Redis会先尝试清除已到期或即将到期的Key(设置过expire信息的key)
    #在删除时,按照过期时间进行删除,最早将要被过期的key将最先被删除
    #如果已到期或即将到期的key删光,仍进行set操作,那么将返回错误
    #此时redis将不再接收写请求,只接收get请求。
    #maxmemory的设置比较适合于把redis当作于类似memcached 的缓存来使用
    # maxmemory <bytes>
    
    # By default Redis asynchronously dumps the dataset on disk. If you can live
    # with the idea that the latest records will be lost if something like a crash
    # happens this is the preferred way to run Redis. If instead you care a lot
    # about your data and don't want to that a single record can get lost you should
    # enable the append only mode: when this mode is enabled Redis will append
    # every write operation received in the file appendonly.aof. This file will
    # be read on startup in order to rebuild the full dataset in memory.
    #
    # Note that you can have both the async dumps and the append only file if you
    # like (you have to comment the "save" statements above to disable the dumps).
    # Still if append only mode is enabled Redis will load the data from the
    # log file at startup ignoring the dump.rdb file.
    #
    # IMPORTANT: Check the BGREWRITEAOF to check how to rewrite the append
    # log file in background when it gets too big.
    #redis 默认每次更新操作后会在后台异步的把数据库镜像备份到磁盘,但该备份非常耗时,且备份不宜太频繁
    #redis 同步数据文件是按上面save条件来同步的
    #如果发生诸如拉闸限电、拔插头等状况,那么将造成比较大范围的数据丢失
    #所以redis提供了另外一种更加高效的数据库备份及灾难恢复方式
    #开启append only 模式后,redis 将每一次写操作请求都追加到appendonly.aof 文件中
    #redis重新启动时,会从该文件恢复出之前的状态。
    #但可能会造成 appendonly.aof 文件过大,所以redis支持BGREWRITEAOF 指令,对appendonly.aof重新整理
    appendonly no
    
    # The name of the append only file (default: "appendonly.aof")
    ##更新日志文件名,默认值为appendonly.aof
    # appendfilename appendonly.aof
    
    # The fsync() call tells the Operating System to actually write data on disk
    # instead to wait 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 if one second passed since the last fsync. Compromise.
    #
    # The default is "everysec" 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 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.
    #
    # If unsure, use "everysec".
    #设置对 appendonly.aof 文件进行同步的频率
    #always 表示每次有写操作都进行同步,everysec 表示对写操作进行累积,每秒同步一次。
    #no表示等操作系统进行数据缓存同步到磁盘,都进行同步,everysec 表示对写操作进行累积,每秒同步一次
    # appendfsync always
    appendfsync everysec
    # appendfsync no
    
    # Virtual Memory allows Redis to work with datasets bigger than the actual
    # amount of RAM needed to hold the whole dataset in memory.
    # In order to do so very used keys are taken in memory while the other keys
    # are swapped into a swap file, similarly to what operating systems do
    # with memory pages.
    #
    # To enable VM just set 'vm-enabled' to yes, and set the following three
    # VM parameters accordingly to your needs.
    #是否开启虚拟内存支持。
    #redis 是一个内存数据库,当内存满时,无法接收新的写请求,所以在redis2.0后,提供了虚拟内存的支持
    #但需要注意的,redis 所有的key都会放在内存中,在内存不够时,只把value 值放入交换区
    #虽使用虚拟内存,但性能基本不受影响,需要注意的是要把vm-max-memory设置到足够来放下所有的key
    vm-enabled no
    # vm-enabled yes
    
    # This is the path of the Redis swap file. As you can guess, swap files
    # can't be shared by different Redis instances, so make sure to use a swap
    # file for every redis process you are running. Redis will complain if the
    # swap file is already in use.
    #
    # The best kind of storage for the Redis swap file (that's accessed at random) 
    # is a Solid State Disk (SSD).
    #
    # *** WARNING *** if you are using a shared hosting the default of putting
    # the swap file under /tmp is not secure. Create a dir with access granted
    # only to Redis user and configure Redis to create the swap file there.
    #设置虚拟内存的交换文件路径,不可多个Redis实例共享
    vm-swap-file /tmp/redis.swap
    
    # vm-max-memory configures the VM to use at max the specified amount of
    # RAM. Everything that deos not fit will be swapped on disk *if* possible, that
    # is, if there is still enough contiguous space in the swap file.
    #
    # With vm-max-memory 0 the system will swap everything it can. Not a good
    # default, just specify the max amount of RAM you can in bytes, but it's
    # better to leave some margin. For instance specify an amount of RAM
    # that's more or less between 60 and 80% of your free RAM.
    #设置开启虚拟内存后,redis将使用的最大物理内存大小。
    #默认为0,redis将把他所有能放到交换文件的都放到交换文件中,以尽量少的使用物理内存
    #即当vm-max-memory设置为0的时候,其实是所有value都存在于磁盘
    #在生产环境下,需要根据实际情况设置该值,最好不要使用默认的 0
    vm-max-memory 0
    
    # Redis swap files is split into pages. An object can be saved using multiple
    # contiguous pages, but pages can't be shared between different objects.
    # So if your page is too big, small objects swapped out on disk will waste
    # a lot of space. If you page is too small, there is less space in the swap
    # file (assuming you configured the same number of total swap file pages).
    #
    # If you use a lot of small objects, use a page size of 64 or 32 bytes.
    # If you use a lot of big objects, use a bigger page size.
    # If unsure, use the default :)
    #设置虚拟内存的页大小
    如果 value 值比较大,如要在 value 中放置博客、新闻之类的所有文章内容,就设大一点
    vm-page-size 32
    
    # Number of total memory pages in the swap file.
    # Given that the page table (a bitmap of free/used pages) is taken in memory,
    # every 8 pages on disk will consume 1 byte of RAM.
    #
    # The total swap size is vm-page-size * vm-pages
    #
    # With the default of 32-bytes memory pages and 134217728 pages Redis will
    # use a 4 GB swap file, that will use 16 MB of RAM for the page table.
    #
    # It's better to use the smallest acceptable value for your application,
    # but the default is large in order to work in most conditions.
    #设置交换文件的总的 page 数量
    #注意page table信息是放在物理内存中,每8个page 就会占据RAM中的 1 个 byte
    #总的虚拟内存大小 = vm-page-size * vm-pages
    vm-pages 134217728
    
    # Max number of VM I/O threads running at the same time.
    # This threads are used to read/write data from/to swap file, since they
    # also encode and decode objects from disk to memory or the reverse, a bigger
    # number of threads can help with big objects even if they can't help with
    # I/O itself as the physical device may not be able to couple with many
    # reads/writes operations at the same time.
    #
    # The special value of 0 turn off threaded I/O and enables the blocking
    # Virtual Memory implementation.
    #设置 VM IO 同时使用的线程数量。
    vm-max-threads 4
    
    # Hashes are encoded in a special way (much more memory efficient) when they
    # have at max a given numer of elements, and the biggest element does not
    # exceed a given threshold. You can configure this limits with the following
    # configuration directives.
    #redis 2.0后引入了 hash 数据结构。 
    #hash 中包含超过指定元素个数并且最大的元素当没有超过临界时,hash 将以zipmap来存储
    #zipmap又称为 small hash,可大大减少内存的使用
    hash-max-zipmap-entries 512
    hash-max-zipmap-value 64
    
    # 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 an hash table
    # that is rhashing, 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
    # active rehashing 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 form 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.
    #是否重置Hash表
    #设置成yes后redis将每100毫秒使用1毫秒CPU时间来对redis的hash表重新hash,可降低内存的使用
    #当使用场景有较为严格的实时性需求,不能接受Redis时不时的对请求有2毫秒的延迟的话,把这项配置为no。
    #如果没有这么严格的实时性要求,可以设置为 yes,以便能够尽可能快的释放内存
    activerehashing yes
    
    

    Redis官方文档对VM的使用提出了一些建议:
    当key很小而value很大时,使用VM的效果会比较好.因为这样节约的内存比较大
    当key不小时,可以考虑使用一些非常方法将很大的key变成很大的value,如可将key,value组合成一个新的value

    最好使用linux ext3 等对稀疏文件支持比较好的文件系统保存你的swap文件
    vm-max-threads参数可设置访问swap文件的线程数,最好不要超过机器的核数;设置为0则所有对swap文件的操作都是串行的,可能会造成比较长时间的延迟,但是对数据完整性有很好的保证
    redis数据存储

    redis的存储分为内存存储、磁盘存储和log文件三部分,配置文件中有三个参数对其进行配置。
    save seconds updates,save配置,指出在多长时间内,有多少次更新操作,就将数据同步到数据文件。可多个条件配合,默认配置了三个条件。

    appendonly yes/no ,appendonly配置,指出是否在每次更新操作后进行日志记录,如果不开启,可能会在断电时导致一段时间内的数据丢失。因为redis本身同步数据文件是按上面的save条件来同步的,所以有的数据会在一段时间内只存在于内存中。

    appendfsync no/always/everysec ,appendfsync配置,no表示等操作系统进行数据缓存同步到磁盘,always表示每次更新操作后手动调用fsync()将数据写到磁盘,everysec表示每秒同步一次。

    总结

    1k => 1000 bytes
    1kb => 1024 bytes
    1m => 1000000 bytes
    1mb => 10241024 bytes
    1g => 1000000000 bytes
    1gb => 10241024*1024 bytes
    Redis 配置中对单位的大小写不敏感,1GB、1Gb和1gB都是相同的。由此也说明,Redis 只支持 bytes,不支持 bit 单位。
    Redis 支持以 “includes” 的方式引入其他配置文件,比如:
    include/path/to/local.conf
    include/path/to/other.conf
    需要注意的是,假如多个一个配置项在不同配置文件中都有定义,则以最后一行读入的为准,就是说后面的配置项会覆盖前面的配置项。
    
    1.1通用配置
    默认情况下,Redis 并不是以 daemon 形式来运行的。通过 daemonize 配置项可以控制Redis的运行形式,如果改为 yes,那么 Redis 就会以 daemon 形式运行:
    daemonize no
    当以 daemon 形式运行时,Redis 会生成一个 pid 文件,默认会生成在 /var/run/Redis.pid 。当然,可以通过 pidfile 来指定 pid 文件生成的位置,比如:
    pidfile /path/to/Redis.pid
    默认情况下,Redis 会响应本机所有可用网卡的连接请求。当然,Redis 允许通过 bind 配置项来指定要绑定的IP,比如:
    bind 192.168.1.2 10.8.4.2
    Redis的默认服务端口是6379,可以通过 port 配置项来修改。如果端口设置为0的话,Redis 便不会监听端口了。
    port 6379
    可是,如果Redis不监听端口,还怎么与外界通信呢?其实Redis还支持通过 unix socket 方式来接收请求。可以通过 unix socket 配置项来指定 unix socket 文件的路径,并通过 unix socket perm 来指定文件的权限。
    unixsocket /tmp/Redis.sock
    unixsocketperm 700
    
    在高 QPS 的环境下需要提高 backlog 的值来避免 TCP 的慢连接问题。想要提高 backlog 的值,除了需要设置 Redis 的 tcp-backlog ,还要同时提高更改 Linux 的配置,否则,Linux内核会默认将其截取为 /proc/sys/net/core/somaxconn 的大小。
    tcp-backlog 511
    当一个 Redis-client 一直没有请求发向 server 端,那么 server 端有权主动关闭这个连接,可以通过timeout 来设置“空闲超时时限”,0表示永不关闭。
    timeout 0
    TCP连接保活策略,可以通过 tcp-keepalive 配置项来进行设置,单位为秒,假如设置为60秒,则 server 端会每60秒向连接空闲的客户端发起一次 ACK 请求,以检查客户端是否已经挂掉,对于无响应的客户端则会关闭其连接。所以关闭一个连接最长需要120秒的时间。如果设置为0,则不会进行保活检测。
    tcp-keepalive 0
    Redis支持通过 loglevel 配置项设置日志等级,共分四级,即 debug、verbose、notice、warning。
    loglevel notice
    Redis也支持通过 logfile 配置项来设置日志文件的生成位置。如果设置为空字符串,则 Redis 会将日志输出到标准输出。假如在 daemon 情况下将日志设置为输出到标准输出,则日志会被写到 /dev/null 中。
    logfile ""
    如果希望日志打印到 syslog 中,也很容易,通过 syslog-enabled 来控制。另外,syslog-ident 还可以指定syslog 里的日志标志,比如:
    syslog-ident Redis
    而且还支持指定 syslog 设备,值可以是 USER 或 LOCAL0-LOCAL7 。具体可以参考 syslog 服务本身的用法。
    syslog-facility local0
    对于 Redis 来说,可以设置其数据库的总数量,假如希望一个 Redis 包含16个数据库,那么设置如下:
    databases 16
    这16个数据库的编号将是0到15。默认的数据库是编号为0的数据库。用户可以使用 select <DBid> 来选择相应的数据库。
    
    1.2快照配置
    快照,主要涉及的是 Redis 的 RDB 持久化相关的配置。
    可以用如下的指令来让数据保存到磁盘上,即控制 RDB 快照功能:
    save <seconds> <changes>
    举例来说:
    save 900 1 //表示每15分钟且至少有1个 key 改变,就触发一次持久化
    save 300 10 //表示每5分钟且至少有10个 key 改变,就触发一次持久化
    save 60 10000 //表示每60秒至少有10000个 key 改变,就触发一次持久化
    如果想禁用 RDB 持久化的策略,只要不设置任何 save 指令就可以,或者给 save 传入一个空字符串参数也可以达到相同效果,就像这样:
    save""
    如果用户开启了 RDB 快照功能,那么在 Redis 持久化数据到磁盘时如果出现失败,默认情况下,Redis 会停止接受所有的写请求。这样做的好处在于可以让用户很明确的知道内存中的数据和磁盘上的数据已经存在不一致了。如果 Redis 不顾这种不一致,一意孤行的继续接收写请求,就可能会引起一些灾难性的后果。
    如果下一次 RDB 持久化成功,Redis 会自动恢复接受写请求。
    当然,如果不在乎这种数据不一致或者有其他的手段发现和控制这种不一致的话完全可以关闭这个功能,以便在快照写入失败时,也能确保 Redis 继续接受新的写请求。配置项如下:
    stop-writes-on-bgsave-error yes
    对于存储到磁盘中的快照,可以设置是否进行压缩存储。如果是的话,Redis 会采用 LZF 算法进行压缩。如果不想消耗 CPU 来进行压缩的话,可以设置为关闭此功能,但是存储在磁盘上的快照会比较大。
    rdbcompression yes
    在存储快照后,我们还可以让 Redis 使用 CRC64 算法来进行数据校验,但是这样做会增加大约10%的性能消耗,如果希望获取到最大的性能提升,可以关闭此功能。
    rdbchecksum yes
    我们还可以设置快照文件的名称,默认是这样配置的:
    dbfilename dump.rdb
    还可以设置这个快照文件存放的路径。比如默认设置就是:
    dir ./db/
    
    1.3主从配置
    Redis 提供了主从同步功能。
    通过 slaveof 配置项可以控制某一个 Redis 作为另一个 Redis 的从服务器,通过指定 IP 和端口来定位到主Redis 的位置。一般情况下建议用户为从 Redis 设置一个不同频率的快照持久化的周期,或者为从 Redis 配置一个不同的服务端口等等。
    slaveof <masterip> <masterport>
    如果主 Redis 设置了验证密码的话(使用 requirepass 来设置),则在从 Redis 的配置中要使用masterauth 来设置校验密码,否则的话,主 Redis 会拒绝从 Redis 的访问请求。
    masterauth <master-password>
    当从 Redis 失去了与主 Redis 的连接,或者主从同步正在进行中时, Redis 该如何处理外部发来的访问请求呢?这里,从 Redis 可以有两种选择:
    第一种选择:如果 slave-serve-stale-data 设置为 yes (默认),则从 Redis 仍会继续响应客户端的读写请求。
    第二种选择:如果 slave-serve-stale-data 设置为 no,则从 Redis 会对客户端的请求返回 “SYNC with master inprogress” ,当然也有例外,当客户端发来 INFO 请求和 SLAVEOF 请求,从 Redis 还是会进行处理。
    可以控制一个从 Redis 是否可以接受写请求。将数据直接写入从 Redis ,一般只适用于那些生命周期非常短的数据,因为在主从同步时,这些临时数据就会被清理掉。自从 Redis2.6 版本之后,默认从 Redis 为只读。
    slave-read-only yes
    只读的从 Redis 并不适合直接暴露给不可信的客户端。为了尽量降低风险,可以使用 rename-command指令来将一些可能有破坏力的命令重命名,避免外部直接调用。比如:
    rename-command CONFIG b8c02d524045429941cc15f59e41cb7be6c52
    从 Redis 会周期性的向主 Redis 发出 PING 包。可以通过 repl_ping_slave_period 指令来控制其周期。默认是10秒。
    repl-ping-slave-period 10
    在主从同步时,可能在这些情况下会有超时发生:
    (1)以从 Redis 的角度来看,当有大规模 IO 传输时。
    (2)以从 Redis 的角度来看,当数据传输或 PING 时,主 Redis 超时
    (3)以主 Redis 的角度来看,在回复从 Redis 的 PING 时,从 Redis 超时
    用户可以设置上述超时的时限,不过要确保这个时限比 repl-ping-slave-period 的值要大,否则每次主Redis 都会认为从 Redis 超时。
    repl-timeout 60
    我们可以控制在主从同步时是否禁用 TCP_NODELAY 。如果开启 TCP_NODELAY ,那么主 Redis 会使用更少的 TCP 包和更少的带宽来向从 Redis 传输数据。但是这可能会增加一些同步的延迟,大概会达到40毫秒左右。如果关闭了 TCP_NODELAY ,那么数据同步的延迟时间会降低,但是会消耗更多的带宽。
    repl-disable-tcp-nodelay no
    我们还可以设置同步队列长度。队列长度( backlog )是主 Redis 中的一个缓冲区,在与从 Redis 断开连接期间,主 Redis 会用这个缓冲区来缓存应该发给从 Redis 的数据。这样的话,当从 Redis 重新连接上之后,就不必重新全量同步数据,只需要同步这部分增量数据即可。
    repl-backlog-size 1mb
    如果主 Redis 等了一段时间之后,还是无法连接到从 Redis ,那么缓冲队列中的数据将被清理掉。我们可以设置主 Redis 要等待的时间长度。如果设置为0,则表示永远不清理。默认是1个小时。
    repl-backlog-ttl 3600
    我们可以给众多的从 Redis 设置优先级,在主 Redis 持续工作不正常的情况,优先级高的从 Redis 将会升级为主 Redis 。而编号越小,优先级越高。比如一个主 Redis 有三个从 Redis ,优先级编号分别为10、100、25,那么编号为10的从 Redis 将会被首先选中升级为主 Redis 。当优先级被设置为0时,这个从Redis 将永远也不会被选中。默认的优先级为100。
    slave-priority 100
    假如主 Redis 发现有超过M个从 Redis 的连接延时大于N秒,那么主 Redis 就停止接受外来的写请求。这是因为从 Redis 一般会每秒钟都向主Redis发出PING,而主Redis会记录每一个从 Redis 最近一次发来 PING 的时间点,所以主 Redis 能够了解每一个从 Redis 的运行情况。
    min-slaves-to-write 3
    min-slaves-max-lag 10
    上面这个例子表示,假如有大于等于3个从 Redis 的连接延迟大于10秒,那么主 Redis 就不再接受外部的写请求。上述两个配置中有一个被置为0,则这个特性将被关闭。默认情况下 min-slaves-to-write 为0,而 min-slaves-max-lag 为10。
    
    1.4 安全配置
    我们可以要求 Redis 客户端在向 Redis-server 发送请求之前,先进行密码验证。由于 Redis 性能非常高,每秒钟可以完成多达15万次的密码尝试,所以最好设置一个足够复杂的密码,否则很容易被黑客破解。
    requirepass chenlongfei
    这里通过 requirepass 将密码设置成我的名字。
    Redis 允许我们对 Redis 指令进行更名,比如将一些比较危险的命令改个名字,避免被误执行。比如可以把 CONFIG 命令改成一个很复杂的名字,这样可以避免外部的调用,同时还可以满足内部调用的需要:
    rename-command CONFIG b840fc02d5240454299c15f59e41cb7be6c89
    我们甚至可以禁用掉 CONFIG 命令,那就是把 CONFIG 的名字改成一个空字符串:
    rename-command CONFIG ""
    但需要注意的是,如果使用 AOF 方式进行数据持久化,或者需要与从 Redis 进行通信,那么更改指令的名字可能会引起一些问题。
    
    1.5 限制配置
    我们可以设置 Redis 同时可以与多少个客户端进行连接。默认情况下为10000个客户端。当无法设置进程文件句柄限制时, Redis 会设置为当前的文件句柄限制值减去32,因为 Redis 会为自身内部处理逻辑留一些句柄出来。
    如果达到了此限制, Redis 则会拒绝新的连接请求,并且向这些连接请求方发出 “max number of clients reached” 以作回应。
    maxclients 10000
    我们甚至可以设置 Redis 可以使用的内存量。一旦到达内存使用上限, Redis 将会试图移除内部数据,移除规则可以通过 maxmemory-policy 来指定。
    如果 Redis 无法根据移除规则来移除内存中的数据,或者我们设置了“不允许移除”,那么 Redis 则会针对那些需要申请内存的指令返回错误信息,比如 SET 、 LPUSH 等。但是对于无内存申请的指令,仍然会正常响应,比如 GET 等。
    maxmemory <bytes>
    需要注意的一点是,如果 Redis 是主 Redis (说明 Redis 有从 Redis ),那么在设置内存使用上限时,需要在系统中留出一些内存空间给同步队列缓存,只有在设置的是“不移除”的情况下,才不用考虑这个因素。
    对于内存移除规则来说, Redis 提供了多达6种的移除规则。他们是:
    (1)volatile-lru:使用 LRU 算法移除过期集合中的 key
    (2)allkeys-lru:使用 LRU 算法移除 key
    (3)volatile-random:在过期集合中移除随机的 key
    (4)allkeys-random:移除随机的 key
    (5)volatile-ttl:移除那些 TTL 值最小的 key ,即那些最近才过期的 key
    (6)noeviction:不进行移除。针对写操作,只是返回错误信息
    无论使用上述哪一种移除规则,如果没有合适的 key 可以移除的话, Redis 都会针对写请求返回错误信息。
    maxmemory-policy volatile-lru
    LRU算法和最小TTL算法都并非是精确的算法,而是估算值。所以可以设置样本的大小。假如 Redis 默认会检查三个 key 并选择其中 LRU 的那个,那么可以改变这个 key 样本的数量。
    maxmemory-samples 3
    
    1.6 AOF配置
    默认情况下, Redis 会异步的将数据持久化到磁盘。这种模式在大部分应用程序中已被验证是很有效的,但是在一些问题发生时,比如断电,则这种机制可能会导致数分钟的写请求丢失。
    如上半部分中介绍的, AOF 是一种更好的保持数据一致性的方式。即使当服务器断电时,也仅会有1秒钟的写请求丢失,当 Redis 进程出现问题且操作系统运行正常时,甚至只会丢失一条写请求。
    官方建议, AOF 机制和 RDB 机制可以同时使用,不会有任何冲突。
    appendonly yes
    我们还可以设置 AOF 文件的名称:
    appendfilename "appendonly.aof"
    fsync()调用,用来告诉操作系统立即将缓存的指令写入磁盘。一些操作系统会“立即”进行,而另外一些操作系统则会“尽快”进行。
    Redis支持三种不同的模式:
    (1)no:不调用 fsync() 。而是让操作系统自行决定 sync 的时间。这种模式下, Redis 的性能会最快。
    (2)always:在每次写请求后都调用 fsync() 。这种模式下, Redis 会相对较慢,但数据最安全。
    (3)everysec:每秒钟调用一次 fsync() 。这是性能和安全的折衷。
    默认情况下为 everysec 。
    appendfsync everysec
    当 fsync 方式设置为 always 或 everysec 时,如果后台持久化进程需要执行一个很大的磁盘IO操作,那么 Redis 可能会在 fsync() 调用时卡住。目前尚未修复这个问题,这是因为即使我们在另一个新的线程中去执行 fsync() ,也会阻塞住同步写调用。
    为了缓解这个问题,我们可以使用下面的配置项,这样的话,当 BGSAVE 或 BGWRITEAOF 运行时, fsync() 在主进程中的调用会被阻止。这意味着当另一路进程正在对 AOF 文件进行重构时, Redis 的持久化功能就失效了,就好像我们设置了 “appendsync none” 一样。如果 Redis 有时延问题,那么可以将下面的选项设置为yes。否则请保持no,因为这是保证数据完整性的最安全的选择。
    no-appendfsync-on-rewrite no
    我们允许 Redis 自动重写 aof 。当 aof 增长到一定规模时, Redis 会隐式调用 BGREWRITEAOF 来重写log文件,以缩减文件体积。
    Redis 是这样工作的: Redis 会记录上次重写时的 aof 大小。假如 Redis 自启动至今还没有进行过重写,那么启动时 aof 文件的大小会被作为基准值。这个基准值会和当前的 aof 大小进行比较。如果当前 aof 大小超出所设置的增长比例,则会触发重写。另外还需要设置一个最小大小,是为了防止在 aof 很小时就触发重写。
    auto-aof-rewrite-percentage 100
    auto-aof-rewrite-min-size 64mb
    如果设置 auto-aof-rewrite-percentage 为0,则会关闭此重写功能。
    指Redis在恢复时,会忽略最后一条可能存在问题的指令,默认值yes。即在 aof 写入时,可能存在指令写错的问题(突然断电,写了一半),这种情况下,yes会log并继续,而no会直接恢复失败。
    aof-load-truncated yes
    
    1.7 LUA脚本配置
    lua 脚本的最大运行时间是需要被严格限制的,单位是毫秒:
    lua-time-limit 5000
    如果此值设置为0或负数,则既不会有报错也不会有时间限制。
    
    1.8 集群设置
    平常的 Redis 实例不能作为集群的节点,只有作为集群节点启动的实例才可以。下面的配置可以是 Redis 实例作为集群节点启动:
    cluster-enabled yes
    每个集群节点都有一个集群配置文件,该文件是由集群节点来创建和维护的,不能人工参与。每个集群节点需要不同的配置文件,所以需要保证同一个系统下的集群节点没有重名的配置文件,建议以端口号标记配置文件。
    cluster-config-file nodes-6379.conf
    当节点超时大于 cluster-node-timeout 的时候后,就会被认为宕机了,单位为毫秒。
    cluster-node-timeout 15000
    Redis 集群有一种 failover (故障转移)机制,即当主 Redis 宕机之后,会有一个最合适的从 Redis 充当主 Redis 。但是,当从 Redis 的数据“太老”了,与住 Redis 的标准数据偏差很大,为了保证数据一致性, Redis 会放弃 failover 。判别从 Redis 的的数据是不是“太老”有两种方法:
    (1)如果有多个从 Redis 可以接替主 Redis 的工作,则它们会交换信息,选取“最佳复制偏移”(接受了原主 Redis 最多的数据同步)的从 Redis 作为下一任主 Redis 。
    (2)每个从Redis计算与原主Redis最后一次数据同步的时间,当最短的时间间隔大于某个临界点的时候,集群则放弃failover。
    方法(2)当中的临界点可以通过配置调节,临界点的计算规则为:
    (node-timeout * slave-validity-factor)+ repl-ping-slave-period
    如node-timeout为30秒,slave-validity-factor为10秒,repl-ping-slave-period为10秒,当与原主Redis最后一次对话的时间间隔超过310秒的时候,集群就会放弃failover。
    当slave-validity-factor太大会使一台数据“太老”的从Redis充当主Redis;而slave-validity-factor太小可能会造成找不到合适的从Redis继任。
    默认的slave-validity-factor为10。
    cluster-slave-validity-factor 10
    考虑一种极端情况,集群有一台主Redis和四台从Redis,从Redis全部挂掉,failover机制有可能造成集群只有主Redis而无从Redis的尴尬境况。为了保证集群的名副其实,可以规定,当从Redis少于某个数量时,拒绝执行failover。
    cluster-migration-barrier 1
    默认情况下,当集群检测到某个哈希槽(hash slot)没有被覆盖(没有任何节点为此服务)会停止接受查询服务,如果集群部分宕机最终会导致整个集群不可用,当哈希槽重新被全覆盖的时候会自动变为可用。如果希望那些哈希槽被覆盖的集群节点继续接受查询服务,需要将cluster-require-full-coverage设置为no。
    cluster-require-full-coverage yes
    
    1.9 慢日志配置
    Redis慢日志是指一个系统进行日志查询超过了指定的时长。这个时长不包括IO操作,比如与客户端的交互、发送响应内容等,而仅包括实际执行查询命令的时间。
    针对慢日志可以设置两个参数,一个是执行时长,单位是微秒,另一个是慢日志的长度。当一个新的命令被写入日志时,最老的一条会从命令日志队列中被移除。单位是微秒,即1000000表示一秒。负数则会禁用慢日志功能,而0则表示强制记录每一个命令。
    slowlog-log-slower-than 10000
    慢日志最大长度,可以随便填写数值,没有上限,但要注意它会消耗内存。可以使用SLOWLOG RESET来重设这个值。
    slowlog-max-len 128
    
    1.10 延迟监控配置
    Redis的延迟监控子系统会在运行时对不同操作取样,以此来收集与延迟相关的数据,这些信息可以通过LATENCY命令以报表的形式呈现给用户。
    系统只会记录那些执行时间等于或大于atency-monitor-threshold的操作,该值默认为0,代表关闭监控,因为收集延迟数据多少会影响Redis的性能。
    latency-monitor-threshold 0
    
    1.11事件通知配置
    Redis可以向客户端通知某些事件的发生。
    例如,键空间(keyspace)时间通知如果开启,一个客户端对Database 0中的“foo”键执行了DEL操作,两条信息会通过Pub/Sub发布出去:
    PUBLISH__keyspace@0__:foo del
    PUBLISH__keyevent@0__:del foo
    可以选择需要发送哪种类型的通知,每种类型用一个字母代表:
    K 键空间事件,发布到“keyspace@<db> prefix”频道
    E 键事件, 发布到“ keyevent@<db> prefix”频道
    g 通用事件,比如 DEL,EXPIRE, RENAME, ...等操作都属于
    $ String操作
    l List操作
    s Set操作
    h Hash操作
    z Sorted set操作
    x 过期操作
    e 驱逐操作(因为内存不足数据被删除)
    A 代表“g$lshzxe”的组合, 所以“AKE”可以代表所有事件
    
    notify-keyspace-events配置以上述的字母组合为参数,举例说明:
    (1)notify-keyspace-events Elg
    当有List操作或通用操作,发布通知到“ keyevent@<db> prefix”频道
    (2)notify-keyspace-events Ex
    当有键的过期操作时,发布通知到“keyevent@0:expired”频道
    默认情况下,notify-keyspace-events的参数为空字符串,代表关闭通知。
    notify-keyspace-events ""
    
    1.12 高级配置
    Hash 在条目数量较小的时候会使用一种高效的内存数据结构编码,当超过某个临界点就会采用另一种存储方式,该临界点由下面的两个配置决定:
    hash-max-ziplist-entries 512
    hash-max-ziplist-value 64
    与Hash类似,较小的List会以一种特殊的编码方式来节省空间,只要List不超过下面的上限:
    list-max-ziplist-entries 512
    list-max-ziplist-value 64
    Set只有在满足下面的条件时才会采用特殊编码方式:Set中存储的恰好都是十进制的整数,而且长度不超过64位(有符号)。数量上限为:
    set-max-intset-entries 512
    同样,有序集合也会采用特殊编码来节省空间,只要不超过上限:
    zset-max-ziplist-entries 128
    zset-max-ziplist-value 64
    RedisHyperLogLog 是用来做基数统计的算法,HyperLogLog 的优点是,在输入元素的数量或者体积非常非常大时,计算基数所需的空间总是固定并且很小的。当HyperLogLog用稀疏式表示法时所用内存超过下面的限制,就会转换成稠密式表示,为了更高的内存利用率,官方建议值为3000。
    hll-sparse-max-bytes 3000
    Redis 在每 100 毫秒时使用 1 毫秒的 CPU时间来对 Redis 的 hash 表进行重新 hash 。当使用场景中有非常严格的实时性需要,不能够接受 Redis 时不时的对请求有 2 毫秒的延迟的话,把这项配置为 no 。
    如果没有这么严格的实时性要求,可以设置为 yes ,以便能够尽可能快的释放内存。
    activerehashing yes
    客户端的输出缓冲区的限制,因为某种原因客户端从服务器读取数据的速度不够快,可用于强制断开连接(一个常见的原因是一个发布 / 订阅客户端消费消息的速度无法赶上生产它们的速度)。
    可以三种不同客户端的方式进行设置:
    (1)normal -> 正常客户端
    (2)slave -> slave 和 MONITOR 客户端
    (3)pubsub -> 至少订阅了一个 pubsub channel 或 pattern 的客户端
    每个client-output-buffer-limit 语法 :
    client-output-buffer-limit<class> <hard limit> <soft limit> <soft seconds> 一旦达到硬限制客户端会立即断开,或者达到软限制并保持达成的指定秒数(连续)。
    例如,如果硬限制为 32 兆字节和软限制为 16 兆字节 /10 秒,如果输出缓冲区的大小达到 32 兆字节,客户端将会立即断开,客户端达到 16 兆字节和连续超过了限制 10 秒,也将断开连接。
    默认 normal 客户端不做限制,因为他们在一个请求后未要求时(以推的方式)不接收数据,只有异步客户端可能会出现请求数据的速度比它可以读取的速度快的场景。
    把硬限制和软限制都设置为 0 来禁用该特性
    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 会按照一定的频率来执行后台任务,比如关闭超时的客户端,清除过期键等。不是所有的任务都会按照相同的频率来执行,但 Redis 依照指定的“ Hz ”值来执行检查任务。
    hz 10
    aof rewrite 过程中,是否采取增量文件同步策略,默认为“yes”。 rewrite 过程中,每32M数据进行一次文件同步,这样可以减少 aof 大文件写入对磁盘的操作次数。
    aof-rewrite-incremental-fsync yes
    

    相关文章

      网友评论

          本文标题:redis配置文件redis.conf参数说明

          本文链接:https://www.haomeiwen.com/subject/tmtptktx.html