基本操作
字符串(strings),散列(hashes),列表(lists), 集合(sets), 有序集合(sorted sets)
Strings 字符串
大多数操作使用Strings存取
EXISTS KEY # 判断值是否存在
move KEY 数据库 # 移除某个数据
set KEY VALUE # 添加数据 若存在则覆盖
get key # 获取数据
del key... # 删除指定的key-value 一个或多个 空格间隔
strlen key # 获知字符串长度
expire KEY TIME(秒) # 设置过期秒数
ttl KEY # 查看过期前剩余时间
type key # 查看key对应value的类型
APPEND KEY VALUE # 追加value到key上 若key不存在,就相当于set
#########
INCR key # 执行自增1操作 key值为数字
INCRBY key value # 执行加value 操作 数字
DECR key # 执行自减1操作 key值为数字
DECRBY KEY VALUE # 执行减value 操作 数字
########
GETRANGE KEY START END #获取key值指定位置,截取字符串,初始0 获取全部getrange key 0 -1 获取倒数俩个字符getrange key -2 -1
SETRANGE KEY STRAT VALUE # 替换指定位置开始的字符串
SETEX KEY TIME VALUE # 设置一个key-value,并添加过期值
SETNX KEY VALUE # 当key不存在时添加key-value
mset KEY1 VALUE1 KEY2 VALUE2 ... # 设置多个key-value
msetnnx key1 value1 key2 value2 # 原子操作,若其中key存在,操作失败
mget key1 key2 ... # 同时获取多个key对应value
getset key value # 组合命令 先get 再set 若key不存在返回nil 若存在则返回值并设置新值
########
127.0.0.1:6673> mset user:1:name lyne user:1:age 12
OK
127.0.0.1:6673> mget user:1:name user:1:age
"lyne"
"12"
########
Lists 列表
可将List作为栈 队列 阻塞队列等。。。
所有的list命令都是用l
开头
lpush key value1 value2 ... # 将一个或多个value 插入到列表 key 头部(左)
rpush key value1 value2 ... # 将一个或多个value 插入到列表 key 尾部(右)
lrange key start end # 获取队列类型的key值
lpop key [count] # 头部(左)删除一个值 count 不输入默认一个
rpop key [count] # 尾部(右)删除一个值 count 不输入默认一个
lindex key index # 通过索引值获取列表某一个值
llen key # 获取列表长度
########
key count value # 移除列表中指定数的的数据的值 默认从左侧开始 精确匹配
ltrim key start end # 修剪列表 只保留指定范围内的values
rpoplpush oldkey newkey # 移除列表最后一个元素 并将他移动到新的列表中
lset key index value # 设置指定位置的元素值
linsert key before|after pivot value # 在列表的另一个元素(pivot)之前|之后插入一个元素(value)
总结
- 列表实际上是一个链表
- 头尾操作效率最高 中间元素效率较低
- key存在则新增数据 不存在则创建新链表
- 若移除所有值 则代表不存在
- 可作用域消息队列 栈
Set 集合
无序不重复集合
set集合中的值是不能重复的 所有的Set命令都是用s
开头
sadd key value1 value2 ... # 往集合key中添加一个或多个元素
smembers key # 获取集合中所有元素
sismember key value # 检查value是否是key中元素
scard key # 获取集合中元素个数
srem key value1 value2 ... # 移除集合中的一个或多个元素
#########
srandmember key [count] # 从集合中随机获取一个元素 count可选:抽取数量
spop key [count] # 随机删除并获取集合中的元素 count可选:抽取数量
sdiff key1 key2 ... #以第一个key为参照,获取不同的元素
sinter key1 key2... #以第一个key为参照,获取相同的元素
suntion key1 key2... #以第一个key为参照,获取所有的元素
suntionstore destination key1 key2 ... #合并set元素 并将结果存入新的set中
Hash (哈希Map集合)
key-value Map集合
所有的Hash命令都是用h
开头
hset key field value # 设置hash里面一个字段的值
hget key field # 获取hash里面一个字段的值
hmset key field1 value1 field2 value2 ... # 设置多个字段的值
hmget key field1 field2 ... # 获取多个字段的值
hgetall key # 获取该key所有字段和值
hdel key field1 field2 ... # 删除map中一个或多个字段
######
hlen key # 获取hash所有字段的数量
hexists key field # 判断该字段是否存于hash中
hkeys key # 获取hash中所有的fields
hvals key # 获取hash中所有的字段的值
hincrby key field value # 将指定字段的值增加给定数字
hsetnx key field value # 原子操作添加字段 若field不存在则成功插入
ZSet 有序集合
再set集合基础上增加了个值
zadd key index1 value1 index2 value2 # 添加一个或多个值,若index存在则覆盖
zrange key start end # 根据指定的index返回数据
zcount key min max # 返回分数范围内成员数量
zcard key # 获取有序集合的成员数
#########
zrangebylex key min max [withscores] # 按字典正序排列返回区间内数据 负无穷:-inf 正无穷: +inf withscores 显示所有信息
zrandgebyscore key min max [withscores] # 返回index从小到大排序的指定区间内数据 负无穷:-inf 正无穷: +inf withscores 显示所有信息
zrevrange key min max # 从大到小排序
Geospatial 地理位置
采用标准格式的参数x,y,所以经度必须在纬度之前。这些坐标的限制是可以被编入索引的,区域面积可以很接近极点但是不能索引。具体的限制,由EPSG:900913 / EPSG:3785 / OSGEO:41001 规定如下:
- 有效的经度从-180度到180度。
- 有效的纬度从-85.05112878度到85.05112878度。
当坐标位置超出上述指定范围时,该命令将会返回一个错误。
geoadd key longitude1 latitude1 member1 longitude2 latitude2 member2 ... # 添加一个或多个空间位置 两极无法参加
geopos key member # 根据value获取经纬度 坐标值
geodist key member1 member2 m|km|ft|mi # 返回两个给定位置之间的距离 unit:指定单位 m(米)|km(千米)|mi(英里)|ft(英尺)
geohash key member # 返回标准的地理空间给Geohash字符串
###########
georadius key longitude1 latitude1 radius m|km|ft|mi # 以给定经纬度为中心,返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。
GEORADIUSBYMEMBER key member radius m|km|ft|mi # 以给定成员元素为中心返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。
HyperLogLogs
基数统计算法
优势:占用的内存固定,2^64的元素秩序12kb内存
劣势:0.81%错误率 (对于统计UV任务,可以忽略不计)
网页UV: 访问网站次数
官网解释:HyperLogLog 是一种概率数据结构,用于计算独特的内容(从技术上讲,这指的是估计一组内容的基数)。通常计算唯一的项目需要使用与想要计数的项目数量成正比的记忆量,因为您需要记住您过去已经看到的元素,以避免多次计数它们。但是,有一组算法将内存换成精度:在 Redis 实现(小于 1%)的情况下,您以标准误差的估计量度结束。此算法的魔力在于,您不再需要使用与计数项数量成正比的内存量,而是可以使用恒定的内存量!12k字节在最坏的情况下,或少得多,如果你的超日志(我们只是叫他们HLL从现在开始)已经看到很少的元素。
Redis 中的 HLL 虽然在技术上是不同的数据结构,但被编码为 Redis 字符串,因此您可以调用序列化 HLL,并将其除绿回服务器。GET``SET
# 存放元素
pfadd key emement1 element2 ...
# 当参数为一个key时,返回存储在HyperLogLog结构体的该变量的近似基数
# 当参数为多个key时,返回这些HyperLogLog并集的近似基数,这个值是将所给定的所有key的HyperLoglog结构合并到一个临时的HyperLogLog结构中计算而得到的.
pfcount key1 key2...
# 合并多个HyperLogLog 合并后的 HyperLogLog 的基数接近于所有输入 HyperLogLog 的可见集合
# 合并得出的 HyperLogLog 会被储存在目标变量(第一个参数)里面, 如果该键并不存在, 那么命令在执行之前, 会先为该键创建一个空的.
pfmerge destkey sourcekey1 sourcekey2 ...
BitMaps 位运算
Bitmaps 位图 操作二进制位来进行记录 只有0与1两个状态
setbit key office value # 设置或者清空key的value(字符串)在offset处的bit值。
getbit key office # 查看office
bitcount key [start end]# 统计字符串被设置为1的bit数. start 和 end 参数的设置和 GETRANGE 命令类似,都可以使用负数值:比如 -1 表示最后一个位,而 -2 表示倒数第二个位,以此类推。
配置文件
Redis.conf
路径:kconfig/redis.conf
打开配置文件 vim redis.conf
unit单位 对大小写不敏感
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.
INCLUDES:可以包含多个配置文件
################################## INCLUDES ###################################
# 在此处包含一个或多个其他配置文件。
# 如果您有一个适用于所有 Redis 服务器的标准模板,但还需要自定义一些每个服务器的设置,
# 这将非常有用。 包含文件可以# 包含其他文件,因此请明智地使用它。
# 注意选项“include”不会被管理员或Redis Sentinel的命令“CONFIG REWRITE”重写。
# 由于 Redis 总是使用最后处理的行作 为配置指令的值,您最好将包含放在此文件的
# 开头以避免在运行时覆盖配置更改。
# 相反,如果您有兴趣使用包含来覆盖配置选项,最好使用包含作为最后一行。
#
# include /path/to/local.conf
# include /path/to/other.conf
MODULES:模块
################################## MODULES #####################################
# 启动时加载模块。 如果服务器无法加载模块,它将中止。 可以使用多个 loadmodule 指令。
#
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so
NETWORK: 网络配置
################################## NETWORK #####################################
# 默认情况下,如果未指定“绑定”配置指令,Redis 会侦听来自服务器上所有可用网络接口的连接。
# 可以使用“bind”配置指令只侦听一个或多个选定的接口,后跟一个或多个 IP 地址。
#
# 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 loopback 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 # 绑定访问IP
bind 0.0.0.0
# 保护模式是一层安全保护,以避免在互联网上打开的Redis实例被访问和利用。
#
# 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.
#
# 服务器只接受来自 IPv4 和 IPv6 环回地址 127.0.0.1 和 ::1 以及来自 Unix 域套接字的客户端的连接。
#
# 默认情况下启用保护模式。 仅当您确定希望来自其他主机的客户端连接到 Redis 时,
# 即使没有配置身份验证,也没有使用“bind”指令显式列出一组特定的接口,您才应该禁用它。
protected-mode yes # 保护模式
# 接受指定端口上的连接,默认为 6379 (IANA #815344)。 如果指定了端口 0,Redis 将不会侦听 TCP 套接字。
port 6673 # Redis 端口设置
# TCP listen() backlog.
#
# 在每秒请求数较高的环境中,您需要大量积压以避免客户端连接缓慢的问题。
# 请注意,Linux 内核会默默地将其截断为 /proc/sys/net/core/somaxconn 的值,
# 因此请确保同时提高 somaxconn 和 tcp_max_syn_backlog 的值以获得所需的效果。
tcp-backlog 511 # TCP连接
# Unix socket.
#
# 指定将用于侦听传入连接的 Unix 套接字的路径。 没有默认值,因此如果未指定,Redis 将不会侦听 Unix 套接字。
#
# unixsocket /tmp/redis.sock
# unixsocketperm 700
# 客户端空闲 N 秒后关闭连接(0 表示禁用)
timeout 0
# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
# equipment in the middle.
#
# 在 Linux 上,指定的值(以秒为单位)是用于发送 ACK 的时间段。
# 请注意,关闭连接需要两倍的时间。 在其他内核上,周期取决于内核配置。
#
# 此选项的合理值为 300 秒,这是从 Redis 3.2.1 开始的新 Redis 默认值。
tcp-keepalive 300
GENERAL 通用配置
################################# GENERAL #####################################
# 默认情况下,Redis 不作为守护进程运行。 如果需要,请使用“是”。
# 请注意,Redis 在守护进程时会在 /var/run/redis.pid 中写入一个 pid 文件。
daemonize yes # 是否以守护(后台)进程的方式进行
# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
# supervised no - no supervision interaction
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
# supervised auto - detect upstart or systemd method based on
# UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
# They do not enable continuous liveness pings back to your supervisor.
supervised no # 管理守护进程
# 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".
#
# 创建一个 pid 文件是最好的努力:如果 Redis 无法创建它,没有什么不好的事情发生,服务器将启动并正常运行。
pidfile /www/server/redis/redis.pid # 如果以后台方式进行,我们需要指定一个PID文件位置
# 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 #日志配置
# 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 "/www/server/redis/redis.log" # 日志文件位置
# 要启用系统记录器的日志记录,只需将 'syslog-enabled' 设置为 yes,
# 并可选择更新其他 syslog 参数以满足您的需要。
# syslog-enabled no
# 指定系统日志标识。
# syslog-ident redis
# 指定系统日志工具。 必须是 USER 或介于 LOCAL0-LOCAL7 之间。
# syslog-facility local0
# 设置数据库数量。 默认数据库是 DB 0,您可以使用 SELECT <dbid>
# 在每个连接的基础上选择不同的数据库,其中 dbid 是 0 和 'databases'-1 之间的数字
databases 16 #数据库数量
# By default Redis shows an ASCII art logo only when started to log to the
# standard output and if the standard output is a TTY. Basically this means
# that normally a logo is displayed only in interactive sessions.
#
# However it is possible to force the pre-4.0 behavior and always show a
# ASCII art logo in startup logs by setting the following option to yes.
always-show-logo yes # 是否显示logo
SNAPSHOTTING 快照
规定时间内执行多少次操作,则会持久化到文件 .rdb .aof
################################ 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 # 如果900s内至少有一个key进行修改 就进行持久化操作
save 300 10 # 300s内至少10个key进行修改 就进行持久化操作
save 60 10000 # 60s内至少10000个key进行修改 就进行持久化操作
# 默认情况下,如果启用了 RDB 快照(至少一个保存点)并且最新的后台保存失败,
# Redis 将停止接受写入。 这将使用户意识到(以一种艰难的方式)数据没有正确地
# 持久保存在磁盘上,否则很可能没有人会注意到并且会发生一些灾难。
#
# 如果后台保存过程再次开始工作,Redis 将自动允许再次写入。
#
# 如果您设置了对 Redis 服务器和持久性的适当监控,您可能需要禁用此功能,
# 以便 Redis 继续照常工作,即使存在磁盘、权限等问题。
stop-writes-on-bgsave-error yes # 持久化如果出错是否需要继续工作
# 转储 .rdb 数据库时使用 LZF 压缩字符串对象?
# 默认设置为“是”,因为它几乎总是胜利。 如果您想在保存子项中节省一些 CPU,
# 请将其设置为“否”,但如果您有可压缩的值或键,数据集可能会更大。
rdbcompression yes # 是否压缩rdb持久化文件 需要一些消耗CPU资源
# 由于 RDB 的第 5 版,CRC64 校验和被放置在文件的末尾。
# 这使得格式更能抵抗损坏,但在保存和加载 RDB 文件时会降低性能(大约 10%),
# 因此您可以禁用它以获得最佳性能。
#
# 在禁用校验和的情况下创建的 RDB 文件的校验和为零,这将告诉加载代码跳过检查。
rdbchecksum yes # 保存rdb文件时 是否进行错误校验
# The filename where to dump the DB
dbfilename dump.rdb # #rdb文件名
# 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 /www/server/redis/ # rdb文件的保存目录
REPLICATION 复制(主从复制阶段使用)
################################# REPLICATION #################################
# Master-Replica replication. Use replicaof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# +------------------+ +---------------+
# | Master | ---> | Replica |
# | (receive writes) | | (exact copy) |
# +------------------+ +---------------+
#
# 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 replicas.
# 2) Redis replicas 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 replicas automatically try to reconnect to masters
# and resynchronize with them.
#
# replicaof <masterip> <masterport>
# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the replica to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the replica request.
#
# masterauth <master-password>
# 当副本失去与主节点的连接时,或者当复制仍在进行中时,副本可以以两种不同的方式运行:
#
# 1) if replica-serve-stale-data is set to 'yes' (the default) the replica will
# still reply to client requests, possibly with out of date data, or the
# data set may just be empty if this is the first synchronization.
#
# 2) if replica-serve-stale-data is set to 'no' the replica will reply with
# an error "SYNC with master in progress" to all the kind of commands
# but to INFO, replicaOF, AUTH, PING, SHUTDOWN, REPLCONF, ROLE, CONFIG,
# SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB,
# COMMAND, POST, HOST: and LATENCY.
#
replica-serve-stale-data yes
# You can configure a replica instance to accept writes or not. Writing against
# a replica instance may be useful to store some ephemeral data (because data
# written on a replica will be easily deleted after resync with the master) but
# may also cause problems if clients are writing to it because of a
# misconfiguration.
#
# Since Redis 2.6 by default replicas are read-only.
#
# Note: read only replicas are not designed to be exposed to untrusted clients
# on the internet. It's just a protection layer against misuse of the instance.
# Still a read only replica exports by default all the administrative commands
# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve
# security of read only replicas using 'rename-command' to shadow all the
# administrative / dangerous commands.
replica-read-only yes
# Replication SYNC strategy: disk or socket.
#
# -------------------------------------------------------
# WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY
# -------------------------------------------------------
#
# New replicas and reconnecting replicas that are not able to continue the replication
# process just receiving differences, need to do what is called a "full
# synchronization". An RDB file is transmitted from the master to the replicas.
# The transmission can happen in two different ways:
#
# 1) Disk-backed: The Redis master creates a new process that writes the RDB
# file on disk. Later the file is transferred by the parent
# process to the replicas incrementally.
# 2) Diskless: The Redis master creates a new process that directly writes the
# RDB file to replica sockets, without touching the disk at all.
#
# With disk-backed replication, while the RDB file is generated, more replicas
# can be queued and served with the RDB file as soon as the current child producing
# the RDB file finishes its work. With diskless replication instead once
# the transfer starts, new replicas arriving will be queued and a new transfer
# will start when the current one terminates.
#
# When diskless replication is used, the master waits a configurable amount of
# time (in seconds) before starting the transfer in the hope that multiple replicas
# will arrive and the transfer can be parallelized.
#
# 对于慢速磁盘和快速(大带宽)网络,无盘复制效果更好。
repl-diskless-sync no
# When diskless replication is enabled, it is possible to configure the delay
# the server waits in order to spawn the child that transfers the RDB via socket
# to the replicas.
#
# This is important since once the transfer starts, it is not possible to serve
# new replicas arriving, that will be queued for the next RDB transfer, so the server
# waits a delay in order to let more replicas arrive.
#
# 延迟以秒为单位指定,默认为 5 秒。 要完全禁用它,只需将其设置为 0 秒,传输将尽快开始。
repl-diskless-sync-delay 5
# Replicas send PINGs to server in a predefined interval. It's possible to change
# this interval with the repl_ping_replica_period option. The default value is 10
# seconds.
#
# repl-ping-replica-period 10
# The following option sets the replication timeout for:
#
# 1) Bulk transfer I/O during SYNC, from the point of view of replica.
# 2) Master timeout from the point of view of replicas (data, pings).
# 3) Replica timeout from the point of view of masters (REPLCONF ACK pings).
#
# It is important to make sure that this value is greater than the value
# specified for repl-ping-replica-period otherwise a timeout will be detected
# every time there is low traffic between the master and the replica.
#
# repl-timeout 60
# Disable TCP_NODELAY on the replica socket after SYNC?
#
# If you select "yes" Redis will use a smaller number of TCP packets and
# less bandwidth to send data to replicas. But this can add a delay for
# the data to appear on the replica side, up to 40 milliseconds with
# Linux kernels using a default configuration.
#
# If you select "no" the delay for data to appear on the replica side will
# be reduced but more bandwidth will be used for replication.
#
# By default we optimize for low latency, but in very high traffic conditions
# or when the master and replicas are many hops away, turning this to "yes" may
# be a good idea.
repl-disable-tcp-nodelay no
# 设置复制积压大小。 backlog是一个buffer,当副本断线一段时间后,会积累副本数据,
# 这样当一个副本想要重新连接的时候,往往不需要完全resync,但是部分resync就足够了,
# 只需要把那部分数据传递给replica 断开连接时错过了。
#
# 复制积压越大,副本可以断开连接的时间越长,以后可以执行部分重新同步。
#
# 只有在至少连接了一个副本时才会分配积压。
#
# repl-backlog-size 1mb
# 在 master 不再连接副本一段时间后,backlog 将被释放。
# 以下选项配置需要经过的秒数,从最后一个副本断开连接的时间开始,以释放积压缓冲区。
#
# Note that replicas never free the backlog for timeout, since they may be
# promoted to masters later, and should be able to correctly "partially
# resynchronize" with the replicas: hence they should always accumulate backlog.
#
# A value of 0 means to never release the backlog.
#
# repl-backlog-ttl 3600
# The replica priority is an integer number published by Redis in the INFO output.
# It is used by Redis Sentinel in order to select a replica to promote into a
# master if the master is no longer working correctly.
#
# A replica with a low priority number is considered better for promotion, so
# for instance if there are three replicas with priority 10, 100, 25 Sentinel will
# pick the one with priority 10, that is the lowest.
#
# However a special priority of 0 marks the replica as not able to perform the
# role of master, so a replica with priority of 0 will never be selected by
# Redis Sentinel for promotion.
#
# By default the priority is 100.
replica-priority 100
# It is possible for a master to stop accepting writes if there are less than
# N replicas connected, having a lag less or equal than M seconds.
#
# The N replicas need to be in "online" state.
#
# The lag in seconds, that must be <= the specified value, is calculated from
# the last ping received from the replica, that is usually sent every second.
#
# This option does not GUARANTEE that N replicas will accept the write, but
# will limit the window of exposure for lost writes in case not enough replicas
# are available, to the specified number of seconds.
#
# For example to require at least 3 replicas with a lag <= 10 seconds use:
#
# min-replicas-to-write 3
# min-replicas-max-lag 10
#
# Setting one or the other to 0 disables the feature.
#
# By default min-replicas-to-write is set to 0 (feature disabled) and
# min-replicas-max-lag is set to 10.
# A Redis master is able to list the address and port of the attached
# replicas in different ways. For example the "INFO replication" section
# offers this information, which is used, among other tools, by
# Redis Sentinel in order to discover replica instances.
# Another place where this info is available is in the output of the
# "ROLE" command of a master.
#
# The listed IP and address normally reported by a replica is obtained
# in the following way:
#
# IP: The address is auto detected by checking the peer address
# of the socket used by the replica to connect with the master.
#
# Port: The port is communicated by the replica during the replication
# handshake, and is normally the port that the replica is using to
# listen for connections.
#
# However when port forwarding or Network Address Translation (NAT) is
# used, the replica may be actually reachable via different IP and port
# pairs. The following two options can be used by a replica in order to
# report to its master a specific set of IP and port, so that both INFO
# and ROLE will report those values.
#
# There is no need to use both the options if you need to override just
# the port or the IP address.
#
# replica-announce-ip 5.5.5.5
# replica-announce-port 1234
SECURITY 安全
################################## SECURITY ###################################
# 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
requirepass foobared # 设置密码
# Command renaming.
#
# It is possible to change the name of dangerous commands in a shared
# environment. For instance the CONFIG command may be renamed into something
# hard to guess so that it will still be available for internal-use tools
# but not available for general clients.
#
# Example:
#
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
#
# It is also possible to completely kill a command by renaming it into
# an empty string:
#
# rename-command CONFIG ""
#
# Please note that changing the name of commands that are logged into the
# AOF file or transmitted to replicas may cause problems.
CLIENTS 客户端
################################### CLIENTS ####################################
# 设置同时连接的最大客户端数。 默认情况下,此限制设置为 10000 个客户端,
#但是如果 Redis 服务器无法配置进程文件限制以允许指定的限制,则允许客户端的
# 最大数量设置为当前文件限制减去 32(因为 Redis 保留了一个 很少有文件描述符供内部使用)。
#
# 一旦达到限制,Redis 将关闭所有新连接,发送错误“达到最大客户端数”。
#
# maxclients 10000 # redis连接最大客户端数
MEMORY MANAGEMENT 内存
############################## MEMORY MANAGEMENT ################################
# 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 replicas attached to an instance with maxmemory on,
# the size of the output buffers needed to feed the replicas 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 replicas is full with DELs of keys evicted triggering the deletion
# of more keys, and so forth until the database is completely emptied.
#
# 如果您附加了副本,建议您为 maxmemory 设置一个下限,
# 以便系统上有一些空闲 RAM 用于副本输出缓冲区
#(但如果策略是“noeviction”,则不需要这样做)。
#
# maxmemory <bytes> # 最大内存容量
# 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 # 内存到达上限之后的处理策略
# 几种策略:
# volatile-lru: 只对设置了国企时间的key进行LRU)(默认策略)
# allkeys-lru: 删除lru算法的key
# vollatile-random: 随机删除即将过期key
# allkeys-random: 随机删除
# vollatile-ttl: 删除即将过期的
# noeviction: 永不过期 返回错误
# LRU、LFU 和最小 TTL 算法不是精确算法而是近似算法(为了节省内存),
# 因此您可以对其进行调整以提高速度或准确性。 对于默认 Redis 将检查五个键
# 并选择最近使用较少的一个,您可以使用以下配置指令更改样本大小。
#
# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs more CPU. 3 is faster but not very accurate.
#
# maxmemory-samples 5
# Starting from Redis 5, by default a replica will ignore its maxmemory setting
# (unless it is promoted to master after a failover or manually). It means
# that the eviction of keys will be just handled by the master, sending the
# DEL commands to the replica as keys evict in the master side.
#
# This behavior ensures that masters and replicas stay consistent, and is usually
# what you want, however if your replica is writable, or you want the replica to have
# a different memory setting, and you are sure all the writes performed to the
# replica are idempotent, then you may change this default (but be sure to understand
# what you are doing).
#
# Note that since the replica by default does not evict, it may end using more
# memory than the one set via maxmemory (there are certain buffers that may
# be larger on the replica, or data structures may sometimes take more memory and so
# forth). So make sure you monitor your replicas and make sure they have enough
# memory to never hit a real out-of-memory condition before the master hits
# the configured maxmemory setting.
#
# replica-ignore-maxmemory yes
LAZY FREEING 懒加载
############################# LAZY FREEING ####################################
# Redis has two primitives to delete keys. One is called DEL and is a blocking
# deletion of the object. It means that the server stops processing new commands
# in order to reclaim all the memory associated with an object in a synchronous
# way. If the key deleted is associated with a small object, the time needed
# in order to execute the DEL command is very small and comparable to most other
# O(1) or O(log_N) commands in Redis. However if the key is associated with an
# aggregated value containing millions of elements, the server can block for
# a long time (even seconds) in order to complete the operation.
#
# For the above reasons Redis also offers non blocking deletion primitives
# such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and
# FLUSHDB commands, in order to reclaim memory in background. Those commands
# are executed in constant time. Another thread will incrementally free the
# object in the background as fast as possible.
#
# DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled.
# It's up to the design of the application to understand when it is a good
# idea to use one or the other. However the Redis server sometimes has to
# delete keys or flush the whole database as a side effect of other operations.
# Specifically Redis deletes objects independently of a user call in the
# following scenarios:
#
# 1) On eviction, because of the maxmemory and maxmemory policy configurations,
# in order to make room for new data, without going over the specified
# memory limit.
# 2) Because of expire: when a key with an associated time to live (see the
# EXPIRE command) must be deleted from memory.
# 3) Because of a side effect of a command that stores data on a key that may
# already exist. For example the RENAME command may delete the old key
# content when it is replaced with another one. Similarly SUNIONSTORE
# or SORT with STORE option may delete existing keys. The SET command
# itself removes any old content of the specified key in order to replace
# it with the specified string.
# 4) During replication, when a replica performs a full resynchronization with
# its master, the content of the whole database is removed in order to
# load the RDB file just transferred.
#
# In all the above cases the default is to delete objects in a blocking way,
# like if DEL was called. However you can configure each case specifically
# in order to instead release memory in a non-blocking way like if UNLINK
# was called, using the following configuration directives:
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
APPEND ONLY MODE AOF设置(持久化)
############################## APPEND ONLY MODE ###############################
# 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).
#
# aof 存储
# 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 # 是否开启aof,默认使用rdb持久化
# The name of the append only file (default: "appendonly.aof")
appendfilename "appendonly.aof" # 持久化的文件名
# 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 不执行同步,操作系统自己同步数据,速度最快
# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
#
# In order to mitigate this problem it's possible to use the following option
# that will prevent fsync() from being called in the main process while a
# BGSAVE or BGREWRITEAOF is in progress.
#
# This means that while another child is saving, the durability of Redis is
# the same as "appendfsync none". In practical terms, this means that it is
# possible to lose up to 30 seconds of log in the worst scenario (with the
# default Linux settings).
#
# If you have latency problems turn this to "yes". Otherwise leave it as
# "no" that is the safest pick from the point of view of durability.
no-appendfsync-on-rewrite no
# Automatic rewrite of the append only file.
# Redis is able to automatically rewrite the log file implicitly calling
# BGREWRITEAOF when the AOF log size grows by the specified percentage.
#
# This is how it works: Redis remembers the size of the AOF file after the
# latest rewrite (if no rewrite has happened since the restart, the size of
# the AOF at startup is used).
#
# This base size is compared to the current size. If the current size is
# bigger than the specified percentage, the rewrite is triggered. Also
# you need to specify a minimal size for the AOF file to be rewritten, this
# is useful to avoid rewriting the AOF file even if the percentage increase
# is reached but it is still pretty small.
#
# Specify a percentage of zero in order to disable the automatic AOF
# rewrite feature.
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
# An AOF file may be found to be truncated at the end during the Redis
# startup process, when the AOF data gets loaded back into memory.
# This may happen when the system where Redis is running
# crashes, especially when an ext4 filesystem is mounted without the
# data=ordered option (however this can't happen when Redis itself
# crashes or aborts but the operating system still works correctly).
#
# Redis can either exit with an error when this happens, or load as much
# data as possible (the default now) and start if the AOF file is found
# to be truncated at the end. The following option controls this behavior.
#
# If aof-load-truncated is set to yes, a truncated AOF file is loaded and
# the Redis server starts emitting a log to inform the user of the event.
# Otherwise if the option is set to no, the server aborts with an error
# and refuses to start. When the option is set to no, the user requires
# to fix the AOF file using the "redis-check-aof" utility before to restart
# the server.
#
# Note that if the AOF file will be found to be corrupted in the middle
# the server will still exit with an error. This option only applies when
# Redis will try to read more data from the AOF file but not enough bytes
# will be found.
aof-load-truncated yes
# When rewriting the AOF file, Redis is able to use an RDB preamble in the
# AOF file for faster rewrites and recoveries. When this option is turned
# on the rewritten AOF file is composed of two different stanzas:
#
# [RDB file][AOF tail]
#
# When loading Redis recognizes that the AOF file starts with the "REDIS"
# string and loads the prefixed RDB file, and continues loading the AOF
# tail.
aof-use-rdb-preamble yes
......