Redis common commands, common errors, configuration techniques, etc. share _redis

Source: Internet
Author: User
Tags allkeys compact hash lua redis time interval volatile strong password

1. Redis View all current key

Copy Code code as follows:

KEYS *

2. View the current Redis configuration information
Copy Code code as follows:

CONFIG Get *

3. misconf Redis is configured to save RDB snapshots, but are currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.

Force stop Redis Snapshot cause redis Run user does not have permission to write RDB files or disk space is full, workaround:

Copy Code code as follows:

Config set Stop-writes-on-bgsave-error No

For example:
Copy Code code as follows:

Set ' name ' Shenhui '
-misconf Redis is configured to save RDB snapshots, but are currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.
Config set Stop-writes-on-bgsave-error No
+ok
Set ' name ' Shenhui '
+ok

4. Redis 127.0.0.1:6379> CONFIG SET logfile "/var/log/redis/redis-server.log"
(Error) ERR Unsupported CONFIG parameter:logfile

LogFile cannot be set dynamically via set

5. (error) OOM command not allowed when used memory >
The MaxMemory option is set, Redis memory usage is up to the upper limit.
You can remove some key by setting the LRU algorithm to free up space.
Default is the expiration time, if the set time does not add the expiration time will result in the data is written full maxmemory.
32-bit systems use up to 3GB of memory if you do not set maxmemory or if you set the 0 64-bit system without limiting memory.

Volatile-lru-> is deleted according to the expiration time generated by the LRU algorithm.
ALLKEYS-LRU-> deletes any key according to the LRU algorithm.
Volatile-random-> deletes the key randomly according to the expiration settings.
Allkeys->random-> no difference randomly deleted.
Volatile-ttl-> is deleted based on the most recent expiration (supplemented by TTL)
Noeviction-> who also does not delete, directly in the write operation returned an error.

6. Reids Log Location

LogFile logging mode, the default value is stdout, if set to stdout and run as a daemon, then the log is redirected to/dev/null, which is not logged.

7. Reids Configuration Parameter detailed

Copy Code code as follows:

#daemonize No by default, Redis does not run in the background, and if you need to run in the background, change the value of the item to Yes
Daemonize Yes
# when Redis is running in the background, Redis the default will put the PID file in/var/run/redis.pid, you can configure to other addresses.
# when running multiple Redis services, you need to specify different PID files and ports
Pidfile/var/run/redis_6379.pid
# Specifies the port on which Redis is running, by default 6379
Port 6379
# in a high concurrency environment, to avoid slow client connectivity issues, you need to set up a high speed background log
Tcp-backlog 511
# Specifies that Redis only receive requests from this IP address, and if not set, all requests will be processed
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1
# Sets the timeout in seconds for client connections. When the client does not issue any instructions during this time, close the connection
# 0 is to turn off this setting
Timeout 0
# TCP KeepAlive
# on Linux, specify the value (in seconds) to send the ACKs time. Note that it takes twice as long to close the connection. The default is 0.
Tcp-keepalive 0
# Specify logging level, production environment recommended notice
# Redis supports a total of four levels: Debug, verbose, notice, warning, default to verbose
# Debug records a lot of information for development and testing
# Varbose Useful information, unlike debug will record so much
# Notice ordinary verbose, often used in the production environment
# warning only very important or serious information will be logged to the log
LogLevel Notice
# Configure log file address
# The default value is stdout, standard output, if the background mode will be output to/dev/null.
Logfile/var/log/redis/redis.log
# Number of available databases
# The default value is 16, the default database is 0, and the database ranges between 0-(database-1)
Databases 16
################################ Snapshot #################################
# Save data to disk in the following format:
# Save
# indicates how many times the update operation will be synchronized to the data file RDB.
# The equivalent of a conditional trigger grab snapshot, which can be combined with multiple conditions
# For example, the settings in the default configuration file set three criteria
# Save 900 1 900 seconds at least 1 keys have been changed
# Save 300 10 300 seconds at least 300 keys have been changed
# Save 60 10000 60 seconds at least 10,000 keys have been changed
# Save 900 1
# Save 300 10
# Save 60 10000
# Background Store error stopped writing.
Stop-writes-on-bgsave-error Yes
# Whether to compress data when stored to the local database (persisted to RDB file), default to Yes
Rdbcompression Yes
# RDB file is direct idol Chcksum
Rdbchecksum Yes
# Local Persistent database file name, default value is Dump.rdb
Dbfilename Dump.rdb
# working Directory
# The path where the files for the database mirroring backup are placed.
# The path and filename are configured separately because Redis writes the state of the current database to a temporary file while the backup is in progress, and the backup completes,
# then replace the temporary file with the file specified above, where the temporary files and the backup files configured above will be placed in this specified path.
# aof files will also be stored under this directory
# Note that there must be a directory, not a file.
dir/var/lib/redis-server/
################################# Replication #################################
# master copy. Set the database as a different database from the database.
# Set the IP address and port of the master service when the native is Slav service, it automatically synchronizes data from master when Redis is started
# slaveof
# When the master service is password-protected (password established with Requirepass)
# Slave service connect Master's password
# Masterauth
# When a connection is lost from the library or replication is in progress, there are two ways to run from the hangar:
# 1 if Slave-serve-stale-data is set to Yes (default setting), the request from the library will continue to respond to the client
# 2 If slave-serve-stale-data means no, any request outside the INFO and SLAVOF commands returns a
# error ' SYNC with Master in progress '
Slave-serve-stale-data Yes
# Configure whether the slave instance accepts writes. Writing slave is useful for storing transient data (which can be easily removed after synchronizing with master data), but is not configured, client writes may send a problem.
# from Redis2.6, the default slave is Read-only
Slaveread-only Yes
# Send pings to the main library at a time interval from the library. You can set this time interval by repl-ping-slave-period the default is 10 seconds
# Repl-ping-slave-period 10
# Repl-timeout Set the main library bulk data transfer time or ping reply interval, the default value is 60 seconds
# Make sure Repl-timeout is larger than repl-ping-slave-period
# Repl-timeout 60
# disable tcp_nodelay after slave socket SYNC
# If you choose Yes, Redis will use a smaller digital TCP packet and less bandwidth to send the data to slave, but this could result in delays in sending data to the slave side and 40 milliseconds for the default configuration of Linux kernel.
# If you select ' No ', the delay in sending data to the slave side is reduced, but more bandwidth will be used for replication.
Repl-disable-tcp-nodelay No
# Set the background log size for replication.
# The larger the replicated background log, the longer it takes to slave disconnect and possibly perform partial replication later.
# The background log is assigned only once when there is at least one slave connection.
# repl-backlog-size 1MB
# after Master is no longer connected to slave, the background log is freed. The following configuration defines the time (in seconds) that needs to be freed after disconnecting from the last slave.
# 0 means never releasing the background log
# Repl-backlog-ttl 3600
# If Master does not work again, then in multiple slave, a slave with the lowest priority value is promoted to master, and a value of 0 indicates that it cannot be promoted to master.
Slave-priority 100
# If there are fewer than N slave connections, and the delay time is <=m seconds, master can configure to stop accepting write operations.
# For example, require at least 3 slave connections and delay <=10 second configuration:
# Min-slaves-to-write 3
# Min-slaves-max-lag 10
# Set 0 to Disabled
# default min-slaves-to-write is 0 (disabled), Min-slaves-max-lag is 10
################################## Safety ###################################
# Set the password that you want to use before any other designation is made after the client connects.
# Warning: Because the Redis speed is very fast, so in a better server, an external user can do a 150K password attempt in a second, which means you need to specify a very strong password to prevent brute force
# Requirepass Foobared
# command Rename.
# in a shared environment, you can rename a relatively dangerous command. For example, rename the CONFIG to a character that is not easily guessed.
Example
# Rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
# If you want to delete a command, simply rename it to a null character "", as follows:
# Rename-command CONFIG ""
################################### constraint ###################################
#设置同一时间最大客户端连接数, the default is unrestricted,
#Redis the number of client connections that can be opened simultaneously is the maximum number of file descriptors that the Redis process can open.
#如果设置 maxclients 0, indicating no restriction.
#当客户端连接数到达限制时, Redis closes the new connection and returns the max number of clients reached error message to the client
# maxclients 10000
# Specify Redis maximum memory limit, Redis will load data into memory at startup, and after maximum memory, Redis will try to clear expired Key according to purge policy
# If Redis cannot provide enough space after the policy is cleared, or if the policy is set to ' noeviction ', commands that use more space will have an error, such as set, Lpush, and so on. But can still read the operation
# Note: Redis The new VM mechanism, which stores the Key in memory, and Value is stored in the swap area
# This option is useful for LRU policies.
# MaxMemory settings are more suitable for using Redis as a memcached cache, rather than as a real DB.
# when using Redis as a real database, memory usage will be a big overhead
# MaxMemory
# What data will Redis choose to delete when memory reaches its maximum value? There are five different ways to choose
# VOLATILE-LRU-> Use the LRU algorithm to remove a key that has been set to expire (LRU: Recently used least recentlyused)
# ALLKEYS-LRU-> use LRU algorithm to remove any key
# volatile-random-> Removes a random key that has set an expiration time
# allkeys->random-> Remove a randomkey, any key
# Volatile-ttl-> Remove the Expiring key (minor TTL)
# noeviction-> Not remove any can, just return a write error
# Note: For the above strategy, if there is no appropriate key can be removed, when written Redis will return an error
# default is: VOLATILE-LRU
# Maxmemory-policy VOLATILE-LRU
# LRU and minimal TTL algorithms are not accurate algorithms, but relatively accurate algorithms (to save memory), you can choose the sample size to detect.
# Redis Default Gray Selection 3 samples for testing, you can set up by maxmemory-samples
# Maxmemory-samples 3
############################## aof###############################
# By default, Redis will back up the database in the background asynchronously to disk, but the backup is very time-consuming, and backup can not be very frequent, if there is such as power rationing, pull Plug and so on, it will result in a larger range of data loss.
# so Redis provides another, more efficient way of database backup and disaster recovery.
# after opening append only mode, Redis appends each write request received to the Appendonly.aof file, and when Redis restarts, the file is restored from the previous state.
# but this will cause appendonly.aof file is too large, so Redis also support the bgrewriteaof instructions, appendonly.aof to reorganize.
# You can open asynchronous dumps and aof at the same time
AppendOnly No
# aof file name (default: "Appendonly.aof")
# Appendfilename Appendonly.aof
# Redis supports three kinds of synchronization aof file policies:
# No: No sync, System to operate. Faster.
# always:always indicates that each write is synchronized. Slow, safest.
# Everysec: Represents a cumulative write operation, synchronized once per second. Compromise.
# The default is "Everysec", which is the best in terms of speed and security compromise.
# If you want Redis to run more efficiently, you can also set it to ' no ' to let the operating system decide when to perform
# or, conversely, to make the data more secure, you can also set to ' always '
# If you are unsure, use ' everysec '.
# Appendfsync Always
Appendfsync everysec
# Appendfsync No
# When the AOF policy is set to always or EVERYSEC, the background processing process (background save or AOF log rewrite) performs a large number of I/O operations
# an Fsync () request is blocked in some Linux configurations. Note that there is no fix now, even if fsync is processing on another thread
# to alleviate this problem, you can set the following parameter No-appendfsync-on-rewrite
No-appendfsync-on-rewrite No
# aof Auto Rewrite
# when the aof file grows to a certain size Redis can invoke bgrewriteaof to rewrite the log file
# It works like this: Redis remembers the size of the file after the last log (if it hasn't been rewritten since it was turned on, the size of the day is determined when the boot is on)
# The base size is compared with the current size. If the current size is larger than the base size, the override feature will start
# at the same time, you need to specify a minimum size for the AOF rewrite, which is used to block the AoF file if the file is small but grows very large
# set percentage to 0 to turn off this feature
Auto-aof-rewrite-percentage 100
Auto-aof-rewrite-min-size 64MB
################################ luascripting #############################
# a Lua script has a maximum execution time of 5000 milliseconds (5 seconds) and an infinite execution time if 0 or a negative number is represented.
Lua-time-limit 5000
############################### #LOW log################################
# Redis slow log records commands that exceed the specified execution time. Execution time does not include I/O calculations, such as connecting clients, returning results, and so on, only the command execution time
# Two parameters can be set slow log: One is to tell Redis to execute more than how much time is recorded in the parameters of Slowlog-log-slower-than (subtle),
# Another is the length of the slow log. The oldest command is removed from the queue when a new command is logged
# The time below is subtle, so 1000000 represents a second.
# Note Specifying a negative number closes the slow log, and setting to 0 forces each command to record
Slowlog-log-slower-than 10000
# There is no limit to the length of the log, just be aware that it consumes memory
# The memory consumed by the slow log can be reclaimed by Slowlog RESET
# The default value of 128 is recommended, and when the slow log exceeds 128, the first entry into the queue is kicked out
Slowlog-max-len 128
################################ Event Notification #############################
# When an event occurs, Redis can notify the Pub/sub client.
# You can select the type of event Redis to notify in the following table. Event types are identified by a single character:
# K Keyspace event, published as _keyspace@_ prefix
# E KeyEvent event, published as _keysevent@_ prefix
# g Generic Event (not specified type), like DEL, EXPIRE, RENAME, ...
# $ String Command
# s Set command
# h Hash Command
# Z ordered set command
# x Expiration event (generated every time key expires)
# e clears events (when key is generated when memory is cleared)
# A G$lshzxe's nickname, so "Ake" means all the events
# notify-keyspace-events with a string parameter consisting of 0 to many characters. The empty string means that the notification is disabled.
# Example: Enable list and common events:
# notify-keyspace-events ELG
# The notifications used by default are disabled because the user typically does not need to change the feature, and the feature has a performance loss.
# Note that if you do not specify at least one of the K or E, no events will be sent.
Notify-keyspace-events ""
############################## Advanced Configuration ###############################
# When the hash contains more than the specified number of elements and the largest element does not exceed the critical
# hash will be stored in a special encoding (greatly reducing memory usage), where you can set these two thresholds
# Redis Hash corresponds to the Value inside the actual is a HashMap, in fact there will be 2 different implementations,
# The members of this Hash are relatively young redis in order to save memory will be similar to a one-dimensional array of storage, rather than using a real HASHMAP structure, the corresponding valueredisobject encoding for Zipmap,
# when the number of members increases, it automatically turns into a real HashMap, at which point encoding is HT.
Hash-max-zipmap-entries 512
Hash-max-zipmap-value 64
# like Hash, multiple small lists are encoded in a specific way to save space.
# list data type node value size less than how many bytes will be in a compact storage format.
List-max-ziplist-entries 512
List-max-ziplist-value 64
# Set data type internal data if all are numeric, and how many nodes are included, the following will be stored in compact format.
Set-max-intset-entries 512
# As with Hashe and list, the ordered set is stored in the specified encoding for space saving in a specified length
# Zsort data Type node value size less than how many bytes will be in a compact storage format.
Zset-max-ziplist-entries 128
Zset-max-ziplist-value 64
# Redis will use 1 milliseconds of CPU time per 100 milliseconds to hash the Redis hash table to reduce memory usage
# When you have a very strict real-time need in your use scenario, you cannot accept Redis's request with a 2 millisecond delay, and configure this to No.
# If you do not have such stringent real-time requirements, you can set to Yes so that you can free up memory as quickly as possible
activerehashing Yes
# The client's output buffer is limited because, for some reason, the client is not fast enough to read data from the server,
# can be used to force a disconnect (a common cause is the speed at which a publish/subscribe client's consumer messages cannot catch up with the production of them).
# can be set in three different client ways:
# Normal-> Client
# slave-> slave and MONITOR client
# pubsub-> At least subscribe to a pubsub channel or pattern client
# each CLIENT-OUTPUT-BUFFER-LIMIT syntax:
# Client-output-buffer-limit
# Once the hard limit is reached the client will disconnect immediately, or reach the soft limit and hold the specified number of seconds (consecutive).
# For example, if the hard limit is 32 megabytes and the soft limit is 16 megabytes/10 seconds, the client will disconnect immediately
# If the size of the output buffer reaches 32 megabytes, the client reaches 16 megabytes and continues to exceed the limit of 10 seconds, the connection will also be disconnected.
# The default normal client does not restrict because they do not receive data (in a push) after a request is not requested.
# only asynchronous clients may have a scenario where the requested data is faster than it can read.
# set both hard and soft limits to 0来 disable this feature
Client-output-buffer-limit Normal 0 0 0
Client-output-buffer-limit slave 256MB 64mb60
Client-output-buffer-limit pubsub 32MB 8mb60
# Redis calls internal functions to perform many background tasks, such as closing the client timeout connection, clearing expired keys, and so on.
# Not all tasks are performed at the same frequency, but Redis performs a check task according to the specified ' Hz ' value.
# By default, "Hz" is set to 10.
# Increasing this value will use more CPUs when the Redis is idle, but at the same time having multiple keys expiring simultaneously will make the redis more responsive, and the timeout can be handled more precisely.
# range is between 1 and 500, but a value of more than 100 is usually not a good idea.
# Most users should use the 10 preset, which is necessary to increase the maximum to 100 only in the case of very low latency.
Hz 10
# When a child node rewrites the aof file, if the following options are enabled, the file is synchronized for each generation of 32M data.
Aof-rewrite-incremental-fsync Yes

8.Redis official documentation on VM usage recommendations:

When your key is small and value is large, using a VM will be better. Because this saves a lot of memory.
When your key is not an hour, consider using some very good methods to turn a large key into a large value, for example, you might consider combining key,value into a new value.
It is best to save your swap file using Linux ext3 and other file systems that are better than sparse file support.
Vm-max-threads This parameter, you can set the number of threads to access the swap file, set the best not to exceed the machine's core, if set to 0, then all the operation of the swap file is serial. It may cause a long delay, but there is a good guarantee of data integrity.
With the VM capabilities, Redis is finally out of the memory limit nightmare, it seems we can call it the Redis database, we can also imagine how many new usage can be produced. Of course, hopefully this feature will not have any effect on the memory storage performance of Redis's original very cow B.

9. Redis Modify persistent path and log path

Copy Code code as follows:

Vim redis.conf
Logfile/data/redis_cache/logs/redis.log #日志路径

Dir/data/redis_cache #持久化路径, revise and remember to copy dump.rdb persistent file to/data/redis_cache

Kill Redis First, copy Dump.rdb, start

10. Clear Redis Cache

Copy Code code as follows:

./REDIS-CLI #进入
Dbsize
Flushall #执行
Exit

11. Delete all keys in the Redis current database

Copy Code code as follows:

Flushdb

12. Delete key in all databases of Redis
Copy Code code as follows:

Flushall

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.