Redis Server Tutorial
In this Redis tutorial we learn how to interact with and manage the server and its clients with special server commands.
We cover how to save the datasets to the disk and restore or import that saved data, how to find more information on clients and how to pause or close those client connections among others.
- What are Redis Server Commands
- How to return all information about the Redis server
- How to save the dataset to the disk (synchronously & asynchronously)
- How to restore or import saved data
- How to list all clients connected to the server
- How to close a client's connection to the server
- How to pause command processing from all clients
- How to get and set the name of a client
- How to get and set configuration parameters and write them to the conf file
What are Redis Server Commands
Redis allows us to interact with and manage the server and its clients with special server commands.
The table below shows all the server commands available in Redis.
Command | Description |
---|---|
BGREWRITEAOF | Used to asynchronously rewrite the append-only file. |
BGSAVE | Used to asynchronously save the dataset to the disk. |
CLIENT KILL [ip:port] [ID client-id] | Used to kill the connection of a client. |
CLIENT LIST | Used to get the list of client connections to the server. |
CLIENT GETNAME | Used to get the name of the current connection. |
CLIENT PAUSE timeout | Used to stop processing commands from the clients for a specified time. |
CLIENT SETNAME connection-name | Used to set the current connection name. |
CLUSTER SLOTS | Used to get an array of Cluster slot to node mappings. |
COMMAND | Used to get an array of Redis command details. |
COMMAND COUNT | Used to get total number of Redis commands. |
COMMAND GETKEYS | Used to extract the keys given a full Redis command. |
COMMAND INFO command-name | Used to get an array of specific Redis command details. |
CONFIG GET parameter | Used to get the value of a configuration parameter. |
CONFIG REWRITE | Used to rewrite the configuration file with the in-memory configuration. |
CONFIG SET parameter value | Used to get a configuration parameter to the given value. |
CONFIG RESETSTAT | Used to reset the stats returned by INFO. |
DBSIZE | Used to return the number of keys in the selected database. |
DEBUG OBJECT key | Used to get debugging information about a key. |
DEBUG SEGFAULT | Used to make the server crash. |
FLUSHALL | Used to remove all the keys from all databases. |
FLUSHDB | Used to remove all the keys from the current database. |
INFO [section] | Used to get information and statistics about the server. |
LASTSAVE | Used to retrieve the UNIX time stamp of the last successful save to the disk. |
MONITOR | Used to listen for all the requests received by the server in real time. |
ROLE | Used to return the role of the instance in the context of replication. |
SAVE | Used to synchronously saves the dataset to the disk. |
SHUTDOWN [NOSAVE] [SAVE] | Used to synchronously saves the dataset to the disk and then shuts down the server . |
SLAVEOF host port | Used to make the server a slave of another instance, or promotes it as a master . |
SLOWLOG subcommand [argument] | Used to manage the Redis slow queries log. |
SYNC | Used for replication. |
TIME | Used to return the current server time. |
We take a deeper look at some of the commands below.
How to return all information about the Redis server
We can get a quick overview with statistics about the server by using the INFO command.
INFO
# Server
redis_version:6.0.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:db63ea56716d515f
redis_mode:standalone
os:Linux 4.19.76-linuxkit x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:8.3.0
process_id:1
run_id:eb1029a95aa9c5c6989f4761aec26edaa6c583ec
tcp_port:6379
uptime_in_seconds:13788
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:9881556
executable:/data/redis-server
config_file:
# Clients
connected_clients:2
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0
# Memory
used_memory:888152
used_memory_human:867.34K
used_memory_rss:7151616
used_memory_rss_human:6.82M
used_memory_peak:888152
used_memory_peak_human:867.34K
used_memory_peak_perc:100.17%
used_memory_overhead:836820
used_memory_startup:802848
used_memory_dataset:51332
used_memory_dataset_perc:60.18%
allocator_allocated:880904
allocator_active:1159168
allocator_resident:3522560
total_system_memory:2087813120
total_system_memory_human:1.94G
used_memory_lua:37888
used_memory_lua_human:37.00K
used_memory_scripts:0
used_memory_scripts_human:0B
number_of_cached_scripts:0
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
allocator_frag_ratio:1.32
allocator_frag_bytes:278264
allocator_rss_ratio:3.04
allocator_rss_bytes:2363392
rss_overhead_ratio:2.03
rss_overhead_bytes:3629056
mem_fragmentation_ratio:8.46
mem_fragmentation_bytes:6305968
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_clients_slaves:0
mem_clients_normal:33972
mem_aof_buffer:0
mem_allocator:jemalloc-5.1.0
active_defrag_running:0
lazyfree_pending_objects:0
# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1603703288
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:0
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size:0
module_fork_in_progress:0
module_fork_last_cow_size:0
# Stats
total_connections_received:4
total_commands_processed:14
instantaneous_ops_per_sec:0
total_net_input_bytes:539
total_net_output_bytes:18979
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
expired_stale_perc:0.00
expired_time_cap_reached_count:0
expire_cycle_cpu_milliseconds:149
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0
tracking_total_keys:0
tracking_total_items:0
tracking_total_prefixes:0
unexpected_error_replies:0
# Replication
role:master
connected_slaves:0
master_replid:11cae53d2996f3a75e8b4b727d25903b90ecb0aa
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
# CPU
used_cpu_sys:6.979082
used_cpu_user:6.335137
used_cpu_sys_children:0.003158
used_cpu_user_children:0.002699
# Modules
# Cluster
cluster_enabled:0
# Keyspace
We can filter the information by using one of these sections as an argument.
INFO clients
# Clients
connected_clients:2
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0
The table below shows the available sections to filter by.
server | clients | memory | persistence | stats |
replication | cpu | modules | cluster | keyspace |
How to save the dataset to the disk (synchronously & asynchronously)
As mentioned before, Redis is an in-memory storage. To save the data permanently, we would still need a database solution like MongoDB.
The BGSAVE command will save the dataset asynchronously in the background in the form of a RDB file.
RPUSH firstname John Jane Jack Jill
BGSAVE
In the example above we create a list called ‘firstname’ with four elements. Then we attempt to save it to the disk with the BGSAVE command.
Redis will immediately return a confirmation message that the process has started, then fork. The parent will continue to serve any clients while the child save the dataset on the disk.
Background saving started
A client can check if the file was saved with the LASTSAVE command.
LASTSAVE
(integer) 1603717970
We can also save the dataset synchronously with the SAVE command.
SAVE
Redis will return an OK status if the operation was successful.
How to restore or import saved data
To restore/import the Redis data saved in the previous section, we simply copy the saved file (dump.rdb) into the Redis directory and restart the server.
To get the directory, use the CONFIG command.
CONFIG get dir
1) "dir"
2) "/data"
We’re currently working in a docker image so our path may look different than yours.
On a typical Linux installation, it should look something like the following.
1) "dir"
2) "/user/USERNAME/redis-v*/src"
Where USERNAME is your installation username and v* is your Redis version number.
How to list all clients connected to the server
We can return information and statistics about all the clients connected to the Redis server by using the CLIENT LIST command.
CLIENT LIST
Redis will output the information in a human-readable format, each client on its own line.
id=4 addr=127.0.0.1:47126 fd=8 name= age=14579 idle=12023 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=ping user=default
id=7 addr=127.0.0.1:47132 fd=9 name= age=11008 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 obl=0 oll=0 omem=0 events=r cmd=client user=default
From the output above, we can see that two clients are connected with a bunch of extra info.
The table below offers a breakdown of each field.
Field | Description |
---|---|
id | Unique 64-bit client ID (introduced in Redis 2.8.12) |
addr | Address/port of the client |
fd | File descriptor corresponding to the socket |
age | Total duration of the connection in seconds |
idle | Idle time of the connection in seconds |
flags | Client flags (see below) |
db | Current database ID |
sub | Number of channel subscriptions |
psub | Number of pattern matching subscriptions |
multi | Number of commands in a MULTI/EXEC context |
qbuf | Query buffer length (0 means no query pending) |
qbuf-free | Free space of the query buffer (0 means the buffer is full) |
obl | Output buffer length |
oll | Output list length (replies are queued in this list when the buffer is full) |
omem | Output buffer memory usage |
events | File descriptor events (see below) |
cmd | Last command played |
How to close a client's connection to the server
We can forcibly close one or more client’s connection the server by using the CLIENT KILL command.
This command has several options depending on which connections we want to close.
Field | Description | Example |
---|---|---|
CLIENT KILL ADDR ip:port | Kill the connection of the client with the specified ip:port | CLIENT KILL ADDR 127.0.0.1:47126 |
CLIENT KILL ID client_id | Kill the connection of the client with the specified ID | CLIENT KILL ID 4 |
CLIENT KILL TYPE type | Kill all connections of type normal (MONITOR included), slave or pubsub | CLIENT KILL TYPE normal |
CLIENT KILL SKIPME yes/no | Skip the client calling the command (Default is yes) | CLIENT KILL SKIPME yes |
How to pause command processing from all clients
We can suspend all Redis clients for a specified amount of time with the CLIENT PAUSE command.
The command accepts the time (in milliseconds) to pause the clients as the argument.
When the CLIENT PAUSE command is executed, it will stop processing all pending commands from normal and pubsub clients. Commands from slaves however, will continue normally.
CLIENT PAUSE timeout_in_milliseconds
CLIENT PAUSE 5000
The example above will pause all pending commands from clients for 5 seconds.
When the specified time has elapsed, the clients are unblocked. This will trigger processing of all the commands in the query buffer from all the clients during the pause.
OK
Redis will immediately return an OK status to the caller, so the PAUSE execution isn’t paused itself.
How to get and set the name of a client
Redis allows us to set the name of the current client with the CLIENT SETNAME command so that it’s possible to identify a client with the CLIENT LIST command.
CLIENT SETNAME connection_name
Note that client names cannot contain spaces, newlines or special characters.
CLIENT SETNAME "MyConnection"
If the operation was successful, Redis will return an OK status.
We can also return the name of the current connection with the CLIENT GETNAME command.
CLIENT GETNAME
"MyConnection"
As mentioned before, we can now identify a client by its name when we run the CLIENT LIST command.
If we run the CLIENT LIST command now, we will see that one of the clients has the name ‘MyConnection’ associated with the name field.
id=4 addr=127.0.0.1:47126 fd=8 name= age=34543 idle=31987 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=ping user=default
id=7 addr=127.0.0.1:47132 fd=9 name=MyConnection age=30972 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 obl=0 oll=0 omem=0 events=r cmd=client user=default
Until a client sets its name explicitly, the name field will be empty.
How to get and set configuration parameters and write them to the conf file
Redis allows us to reconfigure the configuration file on the fly without stopping and restarting the service.
To set the value of a config parameter, we use the CONFIG SET command.
CONFIG SET parameter value
For example, we can change the password for a client with the requirepass parameter.
CONFIG SET requirepass "mypass"
Redis will return with an OK status if the operation was successful.
The list of configuration parameters, and their meaning and intended usage is available in the self-documented example redis.conf shipped into the Redis distribution.
- The self documented redis.conf for Redis 6.0.
- The self documented redis.conf for Redis 5.0.
- The self documented redis.conf for Redis 4.0.
- The self documented redis.conf for Redis 3.2.
- The self documented redis.conf for Redis 3.0.
- The self documented redis.conf for Redis 2.8.
- The self documented redis.conf for Redis 2.6.
- The self documented redis.conf for Redis 2.4.
The SAVE parameter works a little differently with the CONFIG SET command than it does in the redis.conf file.
save 900 1
save 300 10
On the first line, we tell Redis to save after 900 seconds if there is at least 1 change to the dataset.
On the second line we tell Redis to save after 300 seconds if there are at least 10 changes to the dataset.
If we use the CONFIG SET command, the same save configuration would look as follows.
CONFIG SET SAVE "900 1 300 10"
We can also return the value of a parameter with the CONFIG GET command. The first argument is the parameter we want to return.
CONFIG GET SAVE
1) "save"
2) "900 1 300 10"
The save parameter will display the data in this special way. Normally, just the value will be displayed.
CONFIG GET list-max-ziplist-size
In the example above we check what the maximum size of compression is for a list.
1) "list-max-ziplist-size"
2) "-2"
A value of -2 means the maximum size is 8 Kb.
Modifying the configuration file with the CONFIG commands has no effect on the redis.conf file itself. On the next restart of Redis, the old configuration will be used instead.
To apply the changes to the redis.conf file, we have to use the CONFIG REWRITE command.
CONFIG REWRITE