Redis is important component when we want to design scalable system. It is used as cache for our system. So, in this article, we will learn how to use some commands in Redis.
Let’s get started.
Table of contents
- How to install redis-cli
- Connect with local/remote redis server
- Get/set commands
- Check commands
- Query commands
- Modification commands
- Wrapping up
How to install redis-cli
Install redis-cli on Windows
To install it on Windows, we can visit some webpages to download a redis executable file.
Install redis-cli on Ubuntu
Belows are some steps to install redis-cli in Ubuntu.
Update the apt package
sudo apt update
sudo apt install -y redis-tools
Connect with local/remote redis server
By default, Redis runs without username and password, the default port is: 6379.
# Go to the folder of Redis # 1st - Run Redis client in local host redis-cli # 2nd - Connect to the remote server redis-cli -h <ip_addr> -p <port_number> -a <password>
Create / Update data
set key value # set if not exist value in key setnx key value
set phone_type Iphone
Modify key’s name
renamenx <key_name> <new_key_name>
renamenx phone_type phonetype
Check whether key is existed or not
Find all keys with patterns
Especially, if we want to list all keys in Redis.
- Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.
All redis commands are single thread and will block the server. The only difference is that
keyshas the potential of blocking server for longer when querying a large data set.
So, with version 2.8 or later, use
scanis a superior alternative to
keysbecause it does not block the server nor does it consume significant resources.
redis-cli --scan --pattern '*'
Get random key from Redis
Get the data type of the value stored in the key
Get the value of a key depends on its type
# string data type get <key> # hash data type hgetall <key> # list data type lrange <key> 0 -1 # set data type smembers <key> # zset data type zrange <key> 0 -1 withscores
Increment value in key
set num 2 incr num
Increment the integer value of a key by the given amount
incrby key increment
incrby num 5
Increment the float value of a key by the given amount
INCRBYFLOAT key increment
Decrement the integer value of key by one
Decrement the integer value of a key by the given number
decrby key decrement
decrby num 4
Set expiration time for key
expire key <expiration_time_ms>
Returns the number of seconds until a key is deleted
Clear expired time of key
- Understanding about the commands of Redis.