10 Minutes Quick Start Redis

Redis installation

Reprint: https://github.com/jaywcjlove/handbook

Official Compilation and Installation

$ wget http://download.redis.io/releases/redis-4.0.0.tar.gz
$ tar xzvf redis-4.0.0.tar.gz -C /usr/local/
$ cd /usr/local/redis-4.0.0
$ make
$ make test
$ make install 
# The program will execute automatically:
# mkdir -p /usr/local/bin
# cp -pf redis-server /usr/local/bin
# cp -pf redis-benchmark /usr/local/bin
# cp -pf redis-cli /usr/local/bin
# cp -pf redis-check-dump /usr/local/bin
# cp -pf redis-check-aof /usr/local/bin

Test make test error reporting

$ make test
You need tcl 8.5 or newer in order to run the Redis test
make: *** [test] Error 1

This is the need to install tcl

wget http://downloads.sourceforge.net/tcl/tcl8.6.1-src.tar.gz  
sudo tar xzvf tcl8.6.1-src.tar.gz  -C /usr/local/  
cd  /usr/local/tcl8.6.1/unix/  
sudo ./configure  
sudo make  
sudo make install   

Installation through EPEL Source

The source installation problem is that you cannot install the latest or specify Redis versions.

yum --enablerepo=epel -y install redis

If there is no installation source, install the source in the following way.

cd /etc/yum.repos.d/
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

Redis upgrade

First, make sure the following repos, EPEL and REMI are installed:

sudo rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
sudo rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-6.rpm

Check the Redis version in REMI repo by viewing the specified source Redis version with the -- enablerepo=epel parameter:

yum --enablerepo=epel info redis
# Loaded plugins: fastestmirror
# Loading mirror speeds from cached hostfile
#  * base: centos.ustc.edu.cn
#  * epel: mirrors.tuna.tsinghua.edu.cn
#  * extras: centos.ustc.edu.cn
#  * updates: mirrors.zju.edu.cn
# Available Packages
# Name        : redis
# Arch        : x86_64
# Version     : 2.4.10
# Release     : 1.el6
# Size        : 213 k
# Repo        : epel/x86_64
# Summary     : A persistent key-value database
# URL         : http://redis.io
# License     : BSD
# Description : Redis is an advanced key-value store. It is similar to memcached but the data
#             : set is not volatile, and values can be strings, exactly like in memcached, but
#             : also lists, sets, and ordered sets. All this data types can be manipulated with
#             : atomic operations to push/pop elements, add/remove elements, perform server
#             : side union, intersection, difference between sets, and so forth. Redis supports
#             : different kind of sorting abilities.

Then install the relevant dependencies (jemalloc) from EPEL repo:

yum --enablerepo=epel install jemalloc

Before installing, you should stop the old Redis daemon:

service redis stop

Then install the updated version of Eds:

sudo yum --enablerepo=remi install redis

Service management

Restart the Redis daemon and start it automatically when it restarts:

sudo service redis start
sudo chkconfig redis on

Basic Service Operations

## Start up and run in the background
$ redis-server & nohup
## Check whether to start
$ redis-cli ping
## close command
$ redis-cli shutdown

# Command Line Client Start
$ redis-cli start
# start-up
$ service redis start
# Stop it
$ service redis stop

# Command Line Client Start
$ redis-cli -p 6380

# Designated Port Background Start
$ redis-server --port 6380 &

View Version

Check the Redis version currently installed:

# View Redis version
$ redis-cli info | grep redis_version

# View port number
$ redis-cli info | grep tcp_port

Start-up

We will find the directory / usr/local/redis-4.0.0/utils in the Redis installation directory, where there is a script redis_init_script, which is copied to the directory / etc/init.d and named redis:

cp /usr/local/redis-4.0.0/utils/redis_init_script /etc/init.d/redis

Copy redis.conf file to / etc/redis directory

cp /usr/local/redis-4.0.0/redis.conf /etc/redis/6380.conf

Configuration file 6380.conf requires several changes

# Whether to run in the background, yes: running in the background; no: not running in the background (old version default)
daemonize yes

Change permissions by chkconfig Command Check and Set System redis Service Open

chmod +x /etc/init.d/redis
chkconfig redis on

The following two lines of annotations must be released in the header of the / etc/init.d/redis file without setting the prompt service redis does not support chkconfig, which is not supported by the report.

# chkconfig:   2345 90 10
# description:  redis is a persistent key-value database

The above comment means that redis services must be started or shut down at runlevels 2, 3, 4, 5, starting at priority 90 and closing at priority 10.

Redis Start Warning Error Resolution

  1. WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
echo "vm.overcommit_memory=1" > /etc/sysctl.conf  # Or vi/etcsysctl.conf, and reboot to restart the machine
echo 1 > /proc/sys/vm/overcommit_memory  # Effective without the need to start the machine
  1. WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
echo 511 > /proc/sys/net/core/somaxconn

Change configuration

The Redis configuration file is located in the Redis installation directory and is named redis.conf. It has been copied to the / etc/redis directory above, and the configuration file can be edited here in sudo vi /etc/redis/6380.conf.

sudo vi /etc/redis/6380.conf

You can view or set configuration items through the CONFIG command. Configuration Setup Command

## Access redis acquisition
127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
## Enter redis settings
127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE

## Get all configurations
127.0.0.1:6379> CONFIG GET *

## Setting configuration to open notification function
$ redis-cli config set notify-keyspace-events KEA

Setting Request Password

Open the vim/etc/redis/6380.conf configuration file to edit it and change the following two items:

# ...
# requirepass foobared
# Change to the following and change foobared to the password you want to set
requirepass 111111

# bind 127.0.0.1 Remove # Note and change to
bind 0.0.0.0

After that, you can access redis with a password.

redis-cli -h 127.0.0.1 -p 6379 -a 111111

Master-slave architecture configuration

Suppose there are two servers, one is the master and the other is the slave.

Redis Master Information:
  IP: 12.168.1.114
  Port: 6379
 Redis from Information:
  IP: 12.168.1.115
  Port: 6379

Edit the Redis configuration file from the slave machine and find the line at the beginning of # slave of. It should be annotated: # slave of < master IP > < master port > We need to remove the annotation and fill in the IP and port of our own host, such as: slave of 192.168.1.114 6379.

# Slveof <IP of Your Host> <Port of Your Host>
# Change this line to the following
slaveof 192.168.1.114 6379

After the configuration is completed and the slave Redis service is restarted, it enters the redis-cli state of the host. Input: INFO replication can query the role of redis of the current host and which slaves have been connected to the host.

At this point, the master-slave configuration has been completed, and we can test the following:

  1. We go into the redis-cli state of the host and set a value, such as: set mygithub jaywcjlove
  2. We switch to the redis-cli state of the slave machine and get the value we just set to see if it exists: get mygithub. At this point, we can find that we can get the value.
  3. But there is one thing to note: slave library does not have the ability to write data, otherwise it will report errors. Slave libraries have only read-only capabilities.

basic operation

## Command Line Client Start
$ redis-cli

# Test heartbeat
127.0.0.1:6379> ping
PONG

# Set the value of the mykey key key
127.0.0.1:6379> set mykey hello
OK

# Get the value of the mykey key key
127.0.0.1:6379> get mykey
"hello"

## Setting mykey failure event
127.0.0.1:6379> expire mykey 2


# View the current redis configuration information
127.0.0.1:6379> config get *

# Get all the key s
127.0.0.1:6379> keys *

# Delete all keys in redis current database
127.0.0.1:6379> flushdb

127.0.0.1:6379> config get dir

# Number of currently available key s crying
127.0.0.1:6379> dbsize

# Delete key s from all databases
127.0.0.1:6379> flushall

# Sign out
127.0.0.1:6379> exit


# Find out the culprit for slowing Redis down
# This tool allows you to view snapshots of all command statistics.
# How many times have commands been executed?
# The number of milliseconds it takes to execute a command (total and average time per command)
# Simply execute the CONFIG RESETSTAT command to reset, so you can get a completely new statistical result.

127.0.0.1:6379> commandstats
cmdstat_get:calls=78,usec=608,usec_per_call=7.79
cmdstat_setex:calls=5,usec=71,usec_per_call=14.20
cmdstat_keys:calls=2,usec=42,usec_per_call=21.00
cmdstat_info:calls=10,usec=1931,usec_per_call=193.10

Supported data types

Character string

# Start the client and store the string to redis.
redis> SET name forezp
OK
# Take the string:
redis> get name 
"forezp"

Hashes-hash value

redis > HMSET king username forezp password xxdxx age 22
redis > HGETALL king
1) "username"
2) "forezp "
3) "password "
4) "xxdxx "
5) "age "
6) "22"

Lists - Lists

redis> lpush pricess kenny
(integer) 1
redis 127.0.0.1:6379> lpush pricess jolin
(integer) 2
redis 127.0.0.1:6379> lpush pricess mayun
(integer) 3
redis 127.0.0.1:6379> lrange pricess 0 10
1) "kenny"
2) "jolin"
3) "mayun"

Ordered set

redis > ZADD kindom 1 redis
(integer) 1
redis> ZADD kindom 2 mongodb
(integer) 1
redis > ZADD kindom 3 mysql
(integer) 1
redis > ZADD kindom 3 mysql
(integer) 0
redis > ZADD kindom 4 mysql
(integer) 0
redis > ZRANGE kindom 0 10 WITHSCORES
1) "redis"
2) "1"
3) "mongodb"
4) "2"
5) "mysql"
6) "4"

Open Notice

Keyspace event notifications are disabled by default because this feature consumes CPU power unwisely. Use notify-keyspace-events of redis.conf or open notifications through CONFIG SET.

## Setting configuration to open notification function
$ redis-cli config set notify-keyspace-events KEA
## The command line monitors all notifications
$ redis-cli --csv psubscribe '__key*__:*'
Reading messages... (press Ctrl-C to quit)
"psubscribe","__key*__:*",1

Key Value Description

K     Keyspace events, published with __keyspace@<db>__ prefix.  
E     Keyevent events, published with __keyevent@<db>__ prefix.  
g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...  
$     String commands  
l     List commands  
s     Set commands  
h     Hash commands  
z     Sorted set commands  
x     Expired events (events generated every time a key expires)  
e     Evicted events (events generated when a key is evicted for maxmemory)  
A     Alias for g$lshzxe, so that the "AKE" string means all the events. 

Events generated by different commands

According to the list below, different commands produce different types of events. Redis Keyspace Notifications

  • DEL generates a del event for each deleted key.
  • RENAME generates two events, a rename_from event for the source key and a rename_to event for the target key.
  • EXPIRE generates an expired event when the key set expires, or an expired event whenever the key set expires is deleted (see the EXPIRE document for more information).
  • SORT generates a sortstore event when STORE is used to set a new key. When the result list is empty and the STORE option is used, and a key of that name already exists, the key is deleted, so under this condition or a del event is generated.
  • SET and all its variants (SETEX, SETNX,GETSET) generate set events. But SETEX also generates an expire event.
  • MSET generates a separate set event for each key.
  • SETRANGE generates a setrange event.
  • INCR, DECR, INCRBY and DECRBY all generate incrby events.
  • INCRBYFLOAT generates an incrbyfloat event.
  • APPEND generates an append event.
  • LPUSH and LPUSHX generate a single lpush event, even in the variable case.
  • RPUSH and RPUSHX generate a single rpush event, even in the variable case.
  • RPOP generates an rpop event. If the key is deleted because the last element is popped up from the list, another del event occurs.
  • LPOP generates an lpop event. If the key is deleted because the last element is popped up from the list, another del event occurs.
  • LINSERT generates a linsert event.
  • LSET generates an lset event.
  • LREM generates an lrem event. If the result list is empty and the key is deleted, another del event is generated.
  • LTRIM generates an ltrim event. If the result list is empty and the key is deleted, another del event is generated.
  • RPOPLPUSH and BRPOPLPUSH generate an rpop event and an lpush event. In both cases, the order can be guaranteed (lpush events are always passed after rpop events). If the result list is zero in length and the key is deleted, a del event will occur.
  • HSET, HSETNX and HMSET all generate a single hset event.
  • HINCRBY generates a hincrby event.
  • HINCRBYFLOAT generates a hincrbyfloat event.
  • hdel generates a single hdel event. If the result hash is empty and the key is deleted, another del event is generated.
  • sadd generates a single sadd event, even in the variable case.
  • srem generates a single srem event. If the result set is empty and the key is deleted, another del event will occur.
  • SMOVE generates a srem event for the source key and a sadd event for the target key.
  • SPOP generates a spop event. If the result set is empty and the key is deleted, another del event will occur.
  • SINTERSTORE, SUNIONSTORE and SDIFFSTORE generate sinterstore, sunionostore and sdiffstore events respectively. In special cases, the collection is empty and the key that stores the result already exists. Because the key is deleted, a del event is generated.
  • ZINCR generates a zincr event.
  • ZADD generates a single zadd event, even if multiple elements are added. .
  • ZREM generates a single zrem event, even if multiple elements are deleted. When the ordered set of results is empty and keys are generated, an additional del event is generated.
  • ZREMBYSCORE generates a single zrembyscore event. When the ordered set of results is empty and keys are generated, an additional del event is generated.
  • ZREMBYRANK generates a single zrembyrank event. When the ordered set of results is empty and keys are generated, an additional del event is generated.
  • ZINTERSTORE and ZUNIONSTORE generate zinterstore and zunionstore events, respectively. In special cases, the collection is empty and the key that stores the result already exists. Because the key is deleted, a del event is generated.
  • An expired event occurs whenever a key associated with a survival event is deleted from the data set due to expiration.
  • An evicted event occurs whenever a key is eliminated from the data set due to the maxmemory policy to save memory.

Open remote login connection

netstat is used to view port usage, 6379 is the default Redis port.

netstat -nlt|grep 6379
  • - t: Indicates the TCP port explicitly
  • - u: Indicates the UDP port explicitly
  • - l: Show only listener sockets
  • - p: Displays process identifiers and program names, each socket/port belongs to a program.
  • - n: No DNS polling, showing IP (speeding up operation)

Modify firewall configuration

Modify the firewall configuration sudo vi/etc/sysconfig/iptables

-A INPUT -m state --state NEW -m tcp -p tcp --dport 6379 -j ACCEPT

Modify configuration files

Redis protected-mode is a new feature added after 3.2. In Redis.conf's annotations, we can see its specific role and enabling conditions. You can edit and modify the configuration file in sudo vi/etc/redis.conf.

# 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

It is enabled on two conditions:

  1. No bind IP
  2. No access password set

If enabled, Redis cache can only be accessed through lookback ip (127.0.0.1), and if accessed from an extranet, the corresponding error message will be returned:

(error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the lookback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the --portected-mode no option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

Provided native monitoring

Number of clients and connections for current links

redis-cli --stat view the number of clients currently connected, connections, etc.

------- data ------ --------------------- load -------------------- - child -
keys       mem      clients blocked requests            connections
4          1.27M    6       0       17340 (+0)          111
4          1.27M    6       0       17341 (+1)          111
4          1.27M    6       0       17342 (+1)          111
4          1.27M    6       0       17343 (+1)          111

Maximum key value and average key value data in memory

redis-cli --bigkeys can also regularly view the current view situation by specifying the - i parameter for the maximum and average key values currently occupying memory.

# Scanning the entire keyspace to find biggest keys as well as
# average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec
# per 100 SCAN commands (not usually needed).

[00.00%] Biggest string found so far 'asdf.js' with 3 bytes
[00.00%] Biggest string found so far 'wabg-tokeneyJhbGciOiJIUzI1NiJ9.NA.UGGRiB2I42rP-33cIMrcoPub7AzHgDlqHacAKFw1pfE' with 328 bytes
[00.00%] Biggest string found so far 'wabg-token-province' with 231042 bytes

-------- summary -------

Sampled 4 keys in the keyspace!
Total key length in bytes is 180 (avg len 45.00)

Biggest string found 'wabg-token-province' has 231042 bytes

4 strings with 231819 bytes (100.00% of keys, avg size 57954.75)
0 lists with 0 items (00.00% of keys, avg size 0.00)
0 sets with 0 members (00.00% of keys, avg size 0.00)
0 hashs with 0 fields (00.00% of keys, avg size 0.00)
0 zsets with 0 members (00.00% of keys, avg size 0.00)

View the current key situation

redis-cli --scan provides functionality similar to keys * to view the current key situation, which can be expressed regularly

$ redis-cli --scan

sess:K4xh-bxOBrcXpy9kEW87oiy-u7I2sAA5
asdf.js
sess:1tGNZSXW8GyoEQsbtpqkA5tMmSFp_ZIn
wabg-tokeneyJhbGciOiJIUzI1NiJ9.NA.UGGRiB2I42rP-33cIMrcoPub7AzHgDlqHacAKFw1pfE
sess:3e4NGIJd0wf1-RONeTt-FsXQj4EaVNjk
wabg-token-province
sess:UuCLAX2sWZ50fiIO1qvDgulf0XIZRd98
wabg-tokeneyJhbGciOiJIUzI1NiJ9.MQ.6z44GClzAsUED1M_UyxqdREdDKcYFnL9tSqd5ZhLhsY
sess:2HEchaRLYUoaa44IF1bB6mpik7lZjBb4

Native Monitor Monitoring

redis-cli monitor prints all sever received commands and their corresponding client addresses

$ redis-cli monitor
OK
1472626566.218175 [0 127.0.0.1:62862] "info"
1472626571.220948 [0 127.0.0.1:62862] "exists" "aaa"
1472626571.223174 [0 127.0.0.1:62862] "set" "aaa" ""
1472626571.232126 [0 127.0.0.1:62862] "type" "aaa"
1472626571.243697 [0 127.0.0.1:62862] "pttl" "aaa"
1472626571.243717 [0 127.0.0.1:62862] "object" "ENCODING" "aaa"
1472626571.243726 [0 127.0.0.1:62862] "strlen" "aaa"

Configuration instructions

#redis.conf
# Redis configuration file example.
# ./redis-server /path/to/redis.conf

################################## INCLUDES ###################################
#This is useful when you have standard configuration templates but each redis server needs personality settings.
# include /path/to/local.conf
# include /path/to/other.conf

################################ GENERAL #####################################

# Whether to run in the background, yes: running in the background; no: not running in the background (old version default)
daemonize yes

# The parameter in 3.2, whether to turn on the protection mode or not, is turned on by default. If the bind and password are not specified in the configuration.
# When this parameter is turned on, redis will only make local access and deny external access.
# If the password and bind are turned on, they can be turned on. Otherwise, you'd better turn it off and set it to no.

protected-mode yes
# redis process file
pidfile /var/run/redis/redis-server.pid

# The port number that redis listens on.
port 6379

# This parameter determines the length of the completed queue (after three handshakes) in a TCP connection. 
# Of course, this value must be no larger than the value of / proc/sys/net/core/somaxconn defined by the Linux system, which defaults to 511.
# The default parameter value for Linux is 128. When the system has a large amount of concurrency and the client is slow,
# These two parameters can be set together for reference. The default value of this kernel parameter is usually 128, which is not enough for the heavily loaded service program.
# It is usually modified to 2048 or larger. Add: net.core.somaxconn = 2048 in / etc/sysctl.conf, and then execute sysctl -p in the terminal.
tcp-backlog 511

#Specifies that redis only receives requests from that IP address, and if not set, all requests will be processed.
bind 127.0.0.1

# Configure unix socket to allow redis to support listening for local connections.
# unixsocket /var/run/redis/redis.sock
# Configure permissions for unix socket to use files
# unixsocketperm 700

# This parameter is to set the client idle more than timeout, the server will disconnect, for 0, the server will not actively disconnect, can not be less than 0.
timeout 0

# tcp keepalive parameter. If it is not set to 0, use the SO_KEEPALIVE value that configures tcp.
# There are two advantages to using keepalive: detecting the end of the hang. Reduce the problem of intermediate devices that lead to network seemingly connected but have problems with end-to-end ports.
# In the Linux kernel, keep alive is set and redis sends ack to the other end at regular intervals. Detection of end-to-end closure requires twice the set value.
tcp-keepalive 0

# The level of the server-side log is specified. Levels include: debug (a lot of information, easy to develop, test)
# verbose (a lot of useful information, but not much debug level information), notice (appropriate log level, suitable for production environment), warn (only very important information)
loglevel notice

#Specifies the file that records the log. If an empty string is used, the log will be printed to the standard output device. The standard output of redis running in the background is / dev/null.
logfile /var/log/redis/redis-server.log

# Whether to turn on record syslog function
# syslog-enabled no

# The syslog identifier.
# syslog-ident redis

# Sources and equipment of logs
# syslog-facility local0

# The number of databases, the default database used is DB 0. You can select a db through the SELECT command
databases 16

################################ SNAPSHOTTING ################################
# Snapshot configuration
# Commenting on the "save" line of configuration items can invalidate the ability to save the database
# Set the frequency of sedis for database mirroring.
# Change at least one key value in 900 seconds (15 minutes) (database save - persistence) 
# Change at least 10 key values in 300 seconds (5 minutes) (database save-persistence) 
# Change at least 10,000 key values in 60 seconds (1 minute) (database save - persistence)
save 900 1
save 300 10
save 60 10000

# When there is an error in RDB persistence, do you continue to work? yes: can't work, no: can continue to work.
# You can find out if there are errors in RDB persistence by rdb_last_bgsave_status in info
stop-writes-on-bgsave-error yes

# Using compressed rdb file, rdb file compression using LZF compression algorithm, yes: compression, but need some cpu consumption. no: uncompressed, requiring more disk space
rdbcompression yes

# Check rdb files. Starting with the fifth version of rdb format, the checksum of CRC64 will be brought at the end of the rdb file.
# This is also good for file fault tolerance, but when saving rdb files, there will be about 10% performance loss, so if you pursue high performance, you can close the configuration.
rdbchecksum yes

# Name of rdb file
dbfilename dump.rdb

# Data directory, where the database is written. rdb, aof files will also be written in this directory
dir /var/lib/redis

################################# REPLICATION #################################
# The replication option, slave replicates the corresponding master.
# slaveof <masterip> <masterport>

#If master sets requirepass, slave needs master's password to connect to master. Master auth is the password used to configure the master so that it can be authenticated after connecting to the master.
# masterauth <master-password>

#When the slave-serve-stale-data is set to yes (default setting), the slave-serve-stale-data will continue to respond to client requests. 2) If slave-serve-stale-data is set to no, any request except the INFO and SLAVOF commands will return an error "SYNC with master in progress".
slave-serve-stale-data yes

#As a slave server, it is read-only by default and can be modified to NO for writing (not recommended).
slave-read-only yes

#Do you use socket to copy data? Currently redis replication provides two ways, disk and socket. If the new slave cannot be partially synchronized or reconnected, full synchronization will be performed and the master will generate rdb files. There are two ways: the disk mode is that the master creates a new process to save the rdb file to disk, and then passes the rdb file on disk to slave. Socket is a new process created by master, which sends rdb files directly to slave in the form of socket. In disk mode, when an rdb is saved, multiple slaves can share the rdb file. The sockets are replicated sequentially from slave to slave. In the case of slow disk speed and fast network speed, socket mode is recommended.
repl-diskless-sync no

#The delay time for diskless replication is prevented from setting to 0. Once the replication starts, the node will not receive the replication request for the new slave until the next rdb transmission. So it's better to wait for a while and wait for more slaves to connect.
repl-diskless-sync-delay 5

#Slve sends Ping requests to the server at specified intervals. The interval can be set by repl_ping_slave_period, defaulting to 10 seconds.
# repl-ping-slave-period 10

#Copy connection timeout. Both master and slave have timeout settings. Master detects that slave last sent more time than repl-timeout, that is to say, slave is offline and clears the slave information. When slave detects that the last interaction with master took longer than repl-timeout, it considers master offline. It should be noted that repl-timeout needs to set a larger value than repl-ping-slave-period, otherwise timeouts are often detected.
# repl-timeout 60

#Whether to prohibit copying tcp nodelay parameters of tcp links can pass yes or no. The default is no, even with tcp nodelay. If the master sets yes to disable the tcp nodelay settings, the number of packets and the network bandwidth will be reduced when the data is copied to slave. But it can also cause data delays. By default, we recommend smaller latency, but in the case of large data traffic, yes is recommended.
repl-disable-tcp-nodelay no

#Copy buffer size, which is a circular replication buffer used to save the latest replicated commands. So when slave is offline, it does not need to replicate master's data completely. If partial synchronization can be performed, it only needs to replicate some data of buffer to slave to restore the normal replication state. The larger the buffer size, the longer the slave can be offline. The replication buffer allocates memory only when there is a slave connection. Without slave, memory will be released by default of 1m.
# repl-backlog-size 5mb

#master does not slave for a period of time and releases the memory of the replication buffer. repl-backlog-ttl is used to set the length of time. In seconds.
# repl-backlog-ttl 3600

#When master is unavailable, Sentinel elects a master according to slave's priority. The lowest priority slave was elected master. And when it's set to zero, it's never going to be elected.
slave-priority 100

#redis provides a way for masters to stop writing. If min-slaves-to-write is configured, the number of healthy slaves is less than N, mater prohibits writing. At least how many healthy slaves does the master have to survive to execute the write command? Although this configuration does not guarantee that all N slaves will receive master's write operations, it can avoid that master cannot write to avoid data loss when there are not enough healthy slaves. Setting to 0 is to turn off the function.
# min-slaves-to-write 3

#A slave with a delay less than min-slaves-max-lag second is considered a healthy slave.
# min-slaves-max-lag 10

# Set 1 or another to 0 to disable this feature.
# Setting one or the other to 0 disables the feature.
# By default min-slaves-to-write is set to 0 (feature disabled) and
# min-slaves-max-lag is set to 10.

################################## SECURITY ###################################
#The requirepass configuration allows users to authenticate passwords using AUTH commands before using other commands. This allows redis to be used in untrusted networks. To maintain backward compatibility, you can annotate the command because most users do not need authentication. When using requirepass, you need to pay attention, because redis is too fast to authenticate passwords 15 W times per second. Simple passwords are easy to crack, so it's better to use a more complex password.
# requirepass foobared

#Change dangerous commands to other names. For example, the CONFIG command can be renamed to a hard-to-guess command so that users can't use it and internal tools can continue to use it.
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52

#Set to an empty value to disable a command
# rename-command CONFIG ""
################################### LIMITS ####################################

# Set the maximum number of client connections that can connect redis. The default is 10,000 client connections.
# Since redis does not distinguish between client connections or internal open files or slave connections, maxclients is recommended to set the minimum to 32.
# If it exceeds Max clients, redis sends'max number of clients reached'to the new connection and closes the connection.
# maxclients 10000

# Maximum memory capacity for redis configuration. When the memory is full, it needs to be processed with the maxmemory-policy policy policy.
# Note that the output buffer of slave is not calculated in maxmemory. So in order to prevent the host from running out of memory, the recommended maxmemory settings need to be smaller.
# maxmemory <bytes>

# Processing strategy after memory capacity exceeds maxmemory.
# volatile-lru: Use the LRU algorithm to remove the key that sets the expiration time.
# volatile-random: Randomly remove the key that sets the expiration time.
# volatile-ttl: Remove the key that is about to expire and delete it based on the latest expiration time (supplemented by TTL)
# allkeys-lru: Remove any key using the LRU algorithm.
# allkeys-random: Random removal of any key.
# noeviction: No key is removed, just a write error is returned.
# The above expulsion strategies, if redis does not have the appropriate key expulsion, still return errors for writing commands.
# redis will no longer receive write requests, only get requests.
# Writing commands include: set setnx setex append incr decr rpush lpush rpushx lpushx linsert lset rpoplpush Sadd sinter sinterstore Sunion store sdiff sdiff store zadd zincrby zunitore zinterstore hsetnx hmset hincrby incrby by GetSet msettnx exec sort.
# maxmemory-policy noeviction

#The number of samples detected by lru. Using LRU or ttl elimination algorithm, select random sample keys from the list that needs to be eliminated, and select the keys that have the longest idle time to remove.
# maxmemory-samples 5

############################## APPEND ONLY MODE ###############################
#The default redis uses RDB persistence, which is sufficient for many applications. But redis may lose data for several minutes if it goes down halfway. Append Only File is another way to persist according to save strategy, which can provide better persistence characteristics. Redis will write every written data to appendonly.aof file after receiving it. Redis will read the data of this file into memory first and ignore the RDB file at each boot.
appendonly no

#aof file name
appendfilename "appendonly.aof"

# Configuration of aof persistence policy
# no means that fsync is not executed, and the operating system guarantees data synchronization to disk at the fastest speed.
# always means that fsync is executed every time a write is written to ensure that data is synchronized to disk.
# everysec indicates that executing fsync once a second may result in the loss of 1s data.
appendfsync everysec

# When aof rewrites or writes rdb files, it executes a lot of IO.
# At this point, for aof mode of everysec and always, executing fsync can cause blocking for too long.
# The no-appendfsync-on-rewrite field is set to no by default.
# For applications with high latency requirements, this field can be set to yes or no.
# This is a safer choice for persistence features. Setting yes indicates that the new write operation is not fsync during rewrite.
# Temporarily exist in memory, wait for rewrite to complete before writing, default to no, recommend yes. The default fsync policy for Linux is 30 seconds. You may lose 30 seconds of data.
no-appendfsync-on-rewrite no

# aof auto-rewrite configuration. When the current aof file size exceeds what percentage of the previous aof file size is rewritten,
# That is, when the aof file grows to a certain size, Redis can call bgrewriteaof to rewrite the log file.
# The current AOF file size is twice the size of the last AOF file (set to 100) when the log rewrite was done, and the new log rewrite process is automatically started.
auto-aof-rewrite-percentage 100
#Set the minimum aof file size allowed to be rewritten, avoiding rewriting when the specified percentage is reached but the size is still small
auto-aof-rewrite-min-size 64mb

# The aof file may be incomplete at the end. When redis starts, the data of the aof file is loaded into memory.
# Restart may occur after the redis host operating system goes down.
# Especially in ext4 filesystems, there is no data=ordered option (redis downtime or abnormal termination does not cause tail incompleteness.)
# When this happens, you can choose to let redis exit or import as much data as possible. If yes is chosen,
# When truncated AOF files are imported, a log is automatically published to the client and then load ed. If no, the user must manually redis-check-aof to repair the AOF file.
aof-load-truncated yes

################################ LUA SCRIPTING ###############################
# If the maximum time limit (milliseconds) is reached, redis records a log and returns an error.
# When a script exceeds the maximum time limit.
# Only SCRIPT KILL and SHUTDOWN NOSAVE can be used.
# The first one is to kill something without the write command. If you have called write, you can only kill it with the second command.
lua-time-limit 5000

################################ REDIS CLUSTER ###############################
# Cluster switch, default is not open cluster mode.
# cluster-enabled yes

# The name of the cluster configuration file. Each node has a cluster-related configuration file, which persists the information of the cluster.
# This file does not need to be manually configured. This configuration file is generated and updated by Redis. Each Redis cluster node needs a separate configuration file.
# Make sure that the configuration file name does not conflict with the system configuration file name on which the instance runs
# cluster-config-file nodes-6379.conf

# Threshold of node interconnection timeout. Number of milliseconds of cluster node timeouts
# cluster-node-timeout 15000

# When failover occurs, all slaves request to be master, but some slaves may be disconnected from master for some time.
# As a result of data obsolescence, such slaves should not be promoted to master. This parameter is used to determine whether slave node and master disconnect time is too long. The judgment method is:
# Compare slave disconnection time with (node-timeout * slave-validity-factor) + repl-ping-slave-period
# If the node timeout is 30 seconds and the slave-validity-factor is 10, assume that the default repl-ping-slave-period is 10 seconds.
# That is, if slave exceeds 310 seconds, it will not attempt to failover 
# cluster-slave-validity-factor 10

# If the number of slaves of master is larger than this value, slaves can migrate to other isolated masters.
# If this parameter is set to 2, then only when a primary node has two working slave nodes, one of its slave nodes will attempt to migrate.
# cluster-migration-barrier 1

# By default, all slot s in the cluster are responsible for the nodes, and the cluster state is ok to provide services.
# Set to no to provide services when slot s are not fully allocated.
# It is not recommended to open this configuration, which will cause the master of the small partition to accept write requests all the time while partitioning, resulting in a long time of data inconsistency.
# cluster-require-full-coverage yes

################################## SLOW LOG ###################################
###Slog logs are used to record the time-consuming execution of slower commands in redis. When the execution of the command exceeds the specified time, it is recorded in slow log, slog log is stored in memory, so there is no IO operation.
#Requests that take longer to execute than slow log-log-slower-than-that are recorded in the slow log in microseconds, so 1000000 is one second. Note that slow query logs are disabled for negative times, while 0 forces all commands to be recorded.
slowlog-log-slower-than 10000

#Slow query log length. When a new command is written into the log, the oldest record is deleted. There is no limit to the length. Just have enough memory. You can release memory through SLOWLOG RESET.
slowlog-max-len 128

################################ LATENCY MONITOR ##############################
#Delay monitoring function is used to monitor some operations in redis that are slower to execute. LATENCY is used to print time-consuming charts of redis instances when running commands. Record only operations that are greater than or equal to the values set below. 0 is to turn off surveillance. The default delay monitoring function is turned off. If you need to turn it on, it can also be set dynamically through the CONFIG SET command.
latency-monitor-threshold 0

############################# EVENT NOTIFICATION ##############################
#Keyspace notifications enable clients to receive events that alter Redis data sets in some way by subscribing to channels or modes. Because the open key space notification function consumes some CPU s, it is turned off by default.
#The notify-keyspace-events parameter can be any combination of the following characters, which specifies what types of notifications the server should send:
##K-key space notification, all notifications prefixed with _keyspace@
##E-key event notification, all notifications prefixed with _keyevent@
##Notification of generic commands unrelated to g DEL, EXPIRE, RENAME, etc.
##Notification of the $string command
##Notification of l ist commands
##Notification of s-set commands
##Notification of the h hash command
##Notification of z-ordered set commands
##x expiration event: sent whenever an expired key is deleted
##e evict event: sent whenever a key is deleted because of the maxmemory policy
##Alias for parameter A g$lshzxe
#There must be at least one K or E in the input parameters, otherwise, no notification will be distributed regardless of the remaining parameters. For detailed use, refer to http://redis.io/topics/notifications.

notify-keyspace-events "KEA"

############################### ADVANCED CONFIG ###############################
# The amount of data is less than or equal to hash-max-ziplist-entries using ziplist, and greater than hash-max-ziplist-entries using hash.
hash-max-ziplist-entries 512
# Value size is less than or equal to hash-max-ziplist-value using ziplist, greater than hash-max-ziplist-value using hash.
hash-max-ziplist-value 64

# Data volume is less than or equal to list-max-ziplist-entries using ziplist, larger than list-max-ziplist-entries using list.
list-max-ziplist-entries 512
# Value size is less than or equal to list-max-ziplist-value using ziplist, larger than list-max-ziplist-value using list.
list-max-ziplist-value 64

# Data volume is less than or equal to set-max-intset-entries using iniset, larger than set-max-intset-entries using set.
set-max-intset-entries 512

# Data volume is less than or equal to zset-max-ziplist-entries using ziplist, larger than zset-max-ziplist-entries using zset.
zset-max-ziplist-entries 128
# Value size is less than or equal to zset-max-ziplist-value using ziplist, larger than zset-max-ziplist-value using zset.
zset-max-ziplist-value 64

# value size is less than or equal to hll-sparse-max-bytes using sparse data structures.
# More than hll-sparse-max-bytes use dense data structures.
# A value larger than 16,000 is almost useless. The recommended value is about 3,000.
# If the CPU requirement is not high and the space requirement is high, it is suggested to set it to about 10,000.
hll-sparse-max-bytes 3000

# Redis will use 1 millisecond CPU time every 100 milliseconds to re-hash redis hash table, which can reduce memory usage.
# When you have a very strict real-time requirement in your usage scenario and can't accept Redis's occasional delay of 2 milliseconds for requests, configure this as no.
# If there is no such strict real-time requirement, you can set it to yes so that memory can be freed as quickly as possible.
activerehashing yes

# Limiting client output buffers can force clients that do not read data from the server to disconnect, forcing them to shut down slow-moving clients.
# For normal client, the first 0 means to cancel hard limit, the second 0 and the third 0 means to cancel soft limit, and the normal client defaults to cancel limit, because they will not receive data without questioning.
client-output-buffer-limit normal 0 0 0
# For slave client and MONTER client, if client-output-buffer exceeds 256 MB or 64 MB lasts 60 seconds, the server will immediately disconnect the client.
client-output-buffer-limit slave 256mb 64mb 60
# For pubsub client, if the client-output-buffer exceeds 32 MB or 8 MB lasts 60 seconds, the server will immediately disconnect the client.
client-output-buffer-limit pubsub 32mb 8mb 60

# redis performs tasks at a frequency of 1s divided by hz.
hz 10

# When AOF is rewritten, if the aof-rewrite-incremental-fsync switch is turned on, the system will execute fsync every 32MB. This is helpful for writing files to disk and avoids excessive latency peaks.
aof-rewrite-incremental-fsync yes

Keywords: Redis sudo EPEL less

Added by ashmo on Fri, 07 Jun 2019 03:13:41 +0300