How To Change Redis’s Configuration from the Command Line
Introduction
Redis is an open-source, in-memory key-value data store. Redis has several commands that allow you to make changes to the Redis server’s configuration settings on the fly. This tutorial will go over some of these commands, and also explain how to make these configuration changes permanent.
How To Use This Guide
This guide is written as a cheat sheet with self-contained examples. We encourage you to jump to any section that is relevant to the task you’re trying to complete.
The commands shown in this guide were tested on an Ubuntu 18.04 server running Redis version 4.0.9. To set up a similar environment, you can follow Step 1 of our guide on How To Install and Secure Redis on Ubuntu 18.04. We will demonstrate how these commands behave by running them with redis-cli
, the Redis command line interface. Note that if you’re using a different Redis interface — Redli, for example — the exact output of certain commands may differ.
Be aware that managed Redis databases typically do not allow users to alter the configuration file. If you’re working with a Managed Database from DigitalOcean, the commands outlined in this guide will result in errors.
The alternative to running Redis commands in interactive mode is to run them as arguments to the redis-cli command, like so: redis-cli rediscommand; If you want to connect to a remote Redis datastore, you can specify its host and port numbers with the -h and -p flags, respectively. $ docker run -name mydb redis Restart a stopped container $ docker start mydb Stop a container $ docker stop mydb Add metadata to container $ docker run -d label=traefik.backend=jenkins jenkins Build an image from Dockerfile in current directory $ docker build -tag myimage. Manage Containers List running containers.
Changing Redis’s Configuration
The commands outlined in this section will only alter the Redis server’s behavior for the duration of the current session, or until you run config rewrite
which will make them permanent. You can alter the Redis configuration file directly by opening and editing it with your preferred text editor. For example, you can use nano
to do so:
Warning: The config set
command is considered dangerous. By changing your Redis configuration file, it’s possible that you will cause your Redis server to behave in unexpected or undesirable ways. We recommend that you only run the config set
command if you are testing out its behavior or you’re absolutely certain that you want to make changes to your Redis configuration.
It may be in your interest to rename this command to something with a lower likelihood of being run accidentally.
config set
allows you to reconfigure Redis at runtime without having to restart the service. It uses the following syntax:
For example, if you wanted to change the name of the database dump file Redis will produce after you run a save
command, you might run a command like the following:
If the configuration change is valid, the command will return OK
. Otherwise it will return an error.
Note: Not every parameter in the redis.conf
file can be changed with a config set
operation. For example, you cannot change the authentication password defined by the requirepass
parameter.
Making Configuration Changes Permanent
config set
does not permanently alter the Redis instance’s configuration file; it only changes Redis’s behavior at runtime. To edit redis.conf
after running a config-set
command and make the current session’s configuration permanent, run config rewrite
:
This command does its best to preserve the comments and overall structure of the original redis.conf
file, with only minimal changes to match the settings currently used by the server.
Like config set
, if the rewrite is successful config rewrite
will return OK
.
Checking Redis’s Configuration
To read the current configuration parameters of a Redis server, run the config get
command. config get
takes a single argument, which can be either an exact match of a parameter used in redis.conf
or a glob pattern. For example:
Depending on your Redis configuration, this command might return:
You can also return all of the configuration parameters supported by config set
by running config get *
.
Conclusion
This guide details the redis-cli
commands used to make changes to a Redis server’s configuration file on the fly. If there are other related commands, arguments, or procedures you’d like to see outlined in this guide, please ask or make suggestions in the comments below.
For more information on Redis commands, see our tutorial series on How to Manage a Redis Database.
Source link
Redis CLI Cheat Sheet
##Start Redis Server
>redis-server
##Start Redis Client
>redis-cli
127.0.0.1:6379>
##Push list of items to a specific key, retrieve them by range
127.0.0.1:6379> lpush testpush 5 2 3 4
(integer) 4
127.0.0.1:6379> lpush testpush “hello world”
(integer) 5
127.0.0.1:6379> lrange testpush 0 -1
1) “hello world”
2) “4”
3) “3”
4) “2”
5) “5”
127.0.0.1:6379> lrange testpush 0 2
1) “hello world”
2) “4”
3) “3”
##Trim list to contain only specified range of items
127.0.0.1:6379> ltrim testpush 1 4
OK
127.0.0.1:6379> lrange testpush 0 -1
1) “4”
2) “3”
3) “2”
4) “5”
127.0.0.1:6379> lrange testpush 0 -1
1) “5”
2) “5”
3) “add one more”
4) “4”
5) “3”
6) “2”
127.0.0.1:6379> lrem testpush -2 “5”
(integer) 2
127.0.0.1:6379> lrange testpush 0 -1
1) “add one more”
2) “4”
3) “3”
4) “2”
##ZSET store a mapping of members to scores
127.0.0.1:6379> ZADD testzet 1 “one” 2 “two” 3 “three”
(integer) 3
127.0.0.1:6379> ZRANGE testzet 0 10
1) “one”
2) “two”
3) “three”
127.0.0.1:6379> ZRANGE testzet 0 1
1) “one”
2) “two”
127.0.0.1:6379> ZRANK testzet “one”
(integer) 0
127.0.0.1:6379> ZSCORE testzet “one”
“1”
127.0.0.1:6379> ZCOUNT testzet 1 2
(integer) 2
127.0.0.1:6379> ZCARD testzet
(integer) 3
#Set expiration time on key
127.0.0.1:6379> expire testzet 10
(integer) 1
127.0.0.1:6379> ttl testzet
(integer) 0
127.0.0.1:6379> keys *
1) “testpush”
##Counter Operations
127.0.0.1:6379> SET test:1:hit:total 2014
OK
127.0.0.1:6379> SET test:2:hit:total 2014
OK
127.0.0.1:6379> INCR test:1:hit:total
(integer) 2015
127.0.0.1:6379> GET test:1:hit:total
“2015”
127.0.0.1:6379> HSET testhash field1 “yellow”
(integer) 1
127.0.0.1:6379> HSET testhash field2 “blue”
(integer) 1
127.0.0.1:6379> HSET users:test name “yellow apple”
(integer) 1
127.0.0.1:6379> HSET users:test email “yellow.apple@gmail.com”
(integer) 1
127.0.0.1:6379> HSET users:test phone “12345”
(integer) 1
127.0.0.1:6379> HSET users:test visit 100
(integer) 1
127.0.0.1:6379> HINCRBY users:test visit 20
(integer) 120
127.0.0.1:6379> HGET users:testi visit
“120”
127.0.0.1:6379> HGETALL users:test
1) “name”
2) “yellow apple”
3) “email”
4) “yellow.apple@gmail.com”
5) “phone”
6) “12345”
7) “visit”
8) “120”
127.0.0.1:6379> HKEYS users:test
1) “name”
2) “email”
3) “phone”
4) “visit”
127.0.0.1:6379> HVALS users:test
1) “yellow apple”
2) “yellow.apple@gmail.com”
3) “12345”
4) “120”
## Set operations and member control
127.0.0.1:6379> SADD testhset “one”
(integer) 1
127.0.0.1:6379> SADD testhset “two”
(integer) 1
127.0.0.1:6379> SCARD testhset
(integer) 2
127.0.0.1:6379> SPOP testhset
“one”
127.0.0.1:6379> SCARD testhset
(integer) 1
##Publish/Subscribe on channel
127.0.0.1:6379> SUBSCRIBE redisChat
Reading messages… (press Ctrl-C to quit)
1) “subscribe”
2) “redisChat”
3) (integer) 1
1) “message”
2) “redisChat”
3) “Redis is a great caching technique”
1) “message”
2) “redisChat”
3) “hello from publisher”
127.0.0.1:6379> PUBLISH redisChat “Redis is a great caching technique”
(integer) 1
127.0.0.1:6379> PUBLISH redisChat “hello from publisher”
(integer) 1
127.0.0.1:6379> PUBLISH redisChat “hello from publisher”
(integer) 0
127.0.0.1:6379> PUBLISH redisChat “hello from publisher”
(integer) 1
##Redis as message queue
127.0.0.1:6379> RPUSH testQueue a b c
(integer) 3
127.0.0.1:6379> BLPOP testQueue 0
1) “testQueue”
2) “a”
(17.07s)
127.0.0.1:6379>
Web Use Cases
Cache latest items in the user’s home page
Expect: – have live and fast update cache view with limited items, page with uniquely defined key
LPUSH : define unique user page key, insert items to the keyed list with LIFO order
LRANGE: retrieve items by order range
LTRIM: limit items in the cache for the page
LREM: remove items by value and occurrence in the list of page key
Cache items for leaderboards, which items are in sorted set by score
ZADD: add items with their score to the unique key set and sorted with O(log(N)) and updating score causes overwrite and re-sort
ZREVRANGE: get top N items from the set
ZRANK: get item’s rank
Cache items to reorder from user vote, which items are re-ranked with updated score
LPUSH: add items to cache
backend task polls the item list and recompute order, use zadd to set rank
ZADD: update items with score
ZREVRANGE: get top N items from the set
Cache items to be expired by time
Option 1: Sorted Set
-Sorted Set cannot set a TTL to individual items, cannot automatically
-Use ZADD UNIX timestamp to identify expiration time as score, and sorted in the set,
– item as activity + “-” + System.currentTime()
– ttl as System.currentTime() + expiration-period-in-long, UTC
– ZADD myzet ttl item
-Use ZREMRANGEBYSCORE to remove the expired items
– ZREMRANGEBYSCORE mizen -inf (System.currentTime())
-Run a backend job to remove expired items with above command
-Pros: simple and straightforward, single data set to visit, extra info to associate date with data
-Cons: extra cleanup job to maintain
Option 2: Set TTL to whole set by its key
Redis can automatically remove the key based on the expire TTL time
–LPUSH mylist item
-ttl as System.currentTime() + expiration-period-in-long, UTC
–EXPIRE mylist ttl
–TTL mylist
-Pros: no extra clean up job
-Cons: not guarantee cleanup
Cache items as counter, metrics, like usage, hits, which Redis has atomicity data type
Single Counter
-Design namespace for the counter as key, build key with “:” as separator
-Maintain counter through INCR, DECR, SET, GET and also have float as BYFLOAT, BITOP etc.
-Reset counter with GETSET to reset automatically
-Expire counter with EXPIRE
Counter in Hash
-Design namespace for hash as key, build key with “:” as separator
–HSET and HINCRBY
-??Reset counter inside hash
-??Expire counter inside hash
Cache N items in given timer period, like unique visitors
–SADD to add items to set as unique
–SCARD to get size of the set and used it to limit N
–EXPIRE whole set
-Or use ZADD with ttl as score and clean job
Real time analysis of what is happening, for stats, anti-spam, filter
Pub/Sub used as buffer/channel/circle, keeping a map of subscribers and publish them for updates
PUBLISH allows you to push a message into a channel
SUBSCRIBE will listen to a channel
Messages sent by other clients to these channels will be pushed by Redis to all the subscribed clients.
A client subscribed to one or more channels should not issue commands, although it can subscribe and unsubscribe to and from other channels. The replies to subscription and unsubscription operations are sent in the form of messages, so that the client can just read a coherent stream of messages where the first element indicates the type of message.
Format of pushed messages
A message is a Array reply with three elements.
The first element is the kind of message:
subscribe
: means that we successfully subscribed to the channel given as the second element in the reply. The third argument represents the number of channels we are currently subscribed to.unsubscribe
: means that we successfully unsubscribed from the channel given as second element in the reply. The third argument represents the number of channels we are currently subscribed to. When the last argument is zero, we are no longer subscribed to any channel, and the client can issue any kind of Redis command as we are outside the Pub/Sub state.message
: it is a message received as result of a PUBLISH command issued by another client. The second element is the name of the originating channel, and the third argument is the actual message payload.
The second element is the kind of message: channel name
The third element is the message content: string
Pattern on channel and message
A client may receive a single message multiple times if it’s subscribed to multiple patterns matching a published message, or if it is subscribed to both patterns and channels matching the message.
Redis RESP protocol
In RESP, the type of some data depends on the first byte:
- For Simple Strings the first byte of the reply is “+”
- For Errors the first byte of the reply is “-“
- For Integers the first byte of the reply is “:”
- For Bulk Strings the first byte of the reply is “$”
- For Arrays the first byte of the reply is “
*
“
Redis as message queue with LIST structure
RPUSH: as producer to push message into tail of the list, multiple items pushed in the order of leftmost to rightmost
BLPOP: as consumer to get the first message from the list and block if queue is empty
The blocking queue behavior can be used as lock for different primitives, like
Consumer:
LOOP forever
While S (key) returns elements
… process elements
END
BRPOP helper_key
END
Producer: uses transaction
MULTI #location txn
SADD key element
Redis Cli Examples
LPUSH helper_key x
EXEC
Redis execute multiple commands in transaction
MULTI: marker to start a transaction to execute the subsequent command in a queued for atomic
EXEC: executes all previously queued commands in a transaction and restores the connection state to normal.
DISCARD: exit transaction with flushing the queued commands
Error aborts transaction and roll back command since Redis 2.6.5
Redis Cli Commands Cheat Sheet Printable
Transaction lock: WATCH is used to provide a check-and-set (CAS) behavior to Redis transactions.