1. Introduction
In modern application development, fast data reading and writing as well as efficient storage are key to ensuring system performance. Redis, as an open-source in-memory data storage system, is widely used in various scenarios such as caching, real-time data processing, and message queues due to its high performance and rich data structures. It can store multiple data types such as strings, hashes, lists, sets, and sorted sets, and supports a wide range of operation commands, greatly enhancing the flexibility and efficiency of developers.
In practical development, mastering common Redis commands is fundamental to effectively utilizing this powerful tool. Whether building high-concurrency web applications or handling large data sets, understanding how to operate data, manage caches, and monitor performance with Redis commands is crucial. These commands not only simplify the data access process but also offer powerful features like transactions, publish/subscribe mechanisms, and persistence options, allowing developers to focus more on implementing business logic.
This blog will delve into common Redis commands to help readers better understand how to effectively apply these commands in different scenarios. We will gradually introduce the purpose, basic syntax, and usage examples of each command, enabling you to quickly get started in practical development. Additionally, we will share best practices to help you avoid common pitfalls when using Redis, thereby improving system performance and reliability. We hope this blog helps you master Redis usage skills, optimize your application architecture, and provide users with a smoother experience.
2. Summary of Common Redis Commands
2.1 Global Commands Summary
keys: Returns all keys that match the pattern. The following patterns are supported:
h?llo
: Matches "hello", "hallo", and "hxllo" (where "?" represents any single character).h*llo
: Matches "hllo" and "heeeello" (where "*" represents any number of characters, including zero).h[ae]llo
: Matches "hello" and "hallo" but not "hillo" (where "[ae]" represents any character that is either "a" or "e").h[^e]llo
: Matches "hallo", "hbllo", etc., but not "hello" (where "[^e]" represents any character except "e").h[a-b]llo
: Matches "hallo" and "hbllo" (where "[a-b]" represents any character between "a" and "b", including "a" and "b").exists: Checks if a key exists.
del: Deletes the specified key.
expire: Sets an expiration time for a specified key in seconds.
ttl: Queries the expiration time of a key in seconds.
type: Returns the data type of the corresponding key.
object encoding: Queries the internal encoding of a value.
setnx: Sets the key-value pair only if the key does not already exist.
2.2 String Type Commands Summary
Command | Effect | Time Complexity |
---|---|---|
set key value | Sets the value of a key to value | O(1) |
`set key value [ex seconds | px milliseconds] [nx | xx] [keepttl]` |
get key | Retrieves the value of a key | O(1) |
del key [key ...] | Deletes the specified key(s) | O(k), where k is the number of keys |
mset key value [key value ...] | Sets multiple key-value pairs | O(k), where k is the number of keys |
mget key [key ...] | Retrieves values for multiple keys | O(k), where k is the number of keys |
incr key | Increments the value of the specified key by 1 | O(1) |
decr key | Decrements the value of the specified key by 1 | O(1) |
incrby key n | Increments the value of the specified key by n | O(1) |
decrby key n | Decrements the value of the specified key by n | O(1) |
incrbyfloat key n | Increments the value of the specified key by n (float) | O(1) |
append key value | Appends value to the value of the specified key | O(1) |
strlen key | Retrieves the length of the value of the specified key | O(1) |
setrange key offset value | Overwrites part of the value of a specified key starting from offset | O(n), where n is the string length, typically O(1) |
getrange key start end | Retrieves part of the value of the specified key from start to end | O(n), where n is the string length, typically O(1) |
2.3 set key value [ex seconds|px milliseconds] [nx|xx] [keepttl]
This is an extended form of the set
command in Redis, allowing you to specify additional options when setting key-value pairs. The specific meaning is as follows:
key: The key to be set.
value: The value associated with the key.
[ex seconds]: Optional parameter to set the expiration time of the key in seconds.
[px milliseconds]: Optional parameter to set the expiration time of the key in milliseconds.
[nx]: Optional parameter that sets the key only if it does not already exist.
[xx]: Optional parameter that updates the key only if it already exists.
[keepttl]: Optional parameter that preserves the remaining time to live of the key when updating its value.
These options allow you to flexibly control the setting and expiration behavior of keys.
2.4 Hash Type Commands Summary
Command | Effect | Time Complexity |
---|---|---|
hset key field value | Sets the value of a field in a hash | O(1) |
hget key field | Retrieves the value of a field in a hash | O(1) |
hdel key field [field ...] | Deletes one or more fields in a hash | O(k), where k is the number of fields |
hlen key | Returns the number of fields in a hash | O(1) |
hgetall key | Retrieves all field-value pairs in a hash | O(k), where k is the number of fields |
hmget key field [field ...] | Retrieves multiple field-values from a hash | O(k), where k is the number of fields |
hmset key field value [field value ...] | Sets multiple field-values in a hash | O(k), where k is the number of fields |
hexists key field | Checks if a field exists in a hash | O(1) |
hkeys key | Retrieves all field names in a hash | O(k), where k is the number of fields |
hvals key | Retrieves all values in a hash | O(k), where k is the number of values |
hsetnx key field value | Sets the value of a field only if the field does not exist | O(1) |
hincrby key field n | Increments the value of a field in a hash by n | O(1) |
hincrbyfloat key field n | Increments the value of a field in a hash by n (float) | O(1) |
hstrlen key field | Retrieves the length of the value in a field | O(1) |
2.5 List Type Commands Summary
Operation Type | Command | Time Complexity |
---|---|---|
Add | rpush key value [value ...] | O(k), where k is the number of elements |
lpush key value [value ...] | O(k), where k is the number of elements | |
linsert key before | after pivot value | |
Search | lrange key start end | O(s + n), where s is the start offset and n is the range from start to end |
lindex key index | O(n), where n is the index offset | |
llen key | O(1) | |
Delete | lpop key | O(1) |
rpop key | O(1) | |
lrem key count value | O(k), where k is the number of elements | |
ltrim key start end | O(k), where k is the number of elements | |
Modify | lset key index value | O(n), where n is the index offset |
Blocking | blpop brpop | O(1) |
2.6 Set Type Commands Summary
Command | Effect | Time Complexity |
---|---|---|
sadd key element [element ...] | Add one or more elements to the set. Duplicate elements cannot be added. | O(k), where k is the number of elements |
srem key element [element ...] | Remove one or more specified elements from the set. | O(k), where k is the number of elements |
scard key | Return the number of elements in the set. | O(1) |
sismember key element | Check if an element exists in the set, returns 1 if it exists, 0 if not. | O(1) |
srandmember key [count] | Return one or more random elements from the set without removing them. If count is provided, return multiple random elements. | O(n), where n is count |
spop key [count] | Remove and return count number of random elements from the set. | O(n), where n is count |
smembers key | Return all elements of the set. | O(k), where k is the number of elements |
sinter key [key ...] | Return the intersection of one or more sets. | O(m * k), where k is the smallest number of elements in the sets and m is the number of keys |
sinterstore destination key [key ...] | Store the intersection of the given sets in the destination set. | O(N * M), where N is the smallest number of elements in the sets and M is the largest |
sunion key [key ...] | Return the union of one or more sets. | O(k), where k is the total number of elements in all sets |
sunionstore destination key [key ...] | Store the union of the given sets in the destination set. | O(N), where N is the total number of elements in all sets |
sdiff key [key ...] | Return the difference of one or more sets. | O(k), where k is the total number of elements in all sets |
sdiffstore destination key [key ...] | Store the difference of the given sets in the destination set. | O(N), where N is the total number of elements in all sets |
2.7 Sorted Set Type Commands Summary
Command | Effect | Time Complexity |
---|---|---|
zadd key score member [score member ...] | Add or update specified elements with associated scores in a sorted set. | O(k * log(n)), where k is the number of members added, n is the number of elements in the current sorted set |
zcard key | Get the number of elements in the sorted set. | O(1) |
zscore key member | Return the score of the specified element. | O(1) |
zrank key member | Return the rank of the specified element, in ascending order. | O(log(n)), where n is the number of elements in the sorted set |
zrevrank key member | Return the rank of the specified element, in descending order. | O(log(n)), where n is the number of elements in the sorted set |
zrem key member [member ...] | Remove specified elements from the sorted set. | O(k * log(n)), where k is the number of members deleted, n is the number of elements in the sorted set |
zincrby key increment member | Add the specified score to the associated score of the element. | O(log(n)), where n is the number of elements in the sorted set |
zrange key start stop [withscores] | Return elements in the specified range, in ascending order of scores. Can return scores if "withscores" is included. | O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set |
zrevrange key start stop [withscores] | Return elements in the specified range, in descending order of scores. Can return scores if "withscores" is included. | O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set |
zrangebyscore key min max [withscores] | Return elements with scores between min and max. By default, min and max are inclusive. Use '(' to exclude them. Can return scores if "withscores" is included. | O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set |
zrevrangebyscore key max min [withscores] | Return elements with scores between max and min, in descending order. Can return scores if "withscores" is included. | O(k + log(n)), where k is the number of elements retrieved, n is the number of elements in the sorted set |
zpopmax key [count] | Remove and return the count highest-scored elements. | O(log(N) * M) |
zpopmin key [count] | Remove and return the count lowest-scored elements. | O(log(N) * M) |
bzpopmax key [count] timeout | Blocking version of zpopmax. | O(log(N)) |
bzpopmin key [count] timeout | Blocking version of zpopmin. | O(log(N)) |
zcount key min max | Return the number of elements with scores between min and max. By default, min and max are inclusive. Use '(' to exclude them. | O(log(n)), where n is the number of elements in the sorted set |
zremrangebyrank key start stop | Remove elements in the specified range by rank, inclusive. | O(k + log(n)), where k is the number of elements removed, n is the number of elements in the sorted set |
zremrangebyscore key min max | Remove elements in the specified range by score, inclusive. | O(k + log(n)), where k is the number of elements removed, n is the number of elements in the sorted set |
zinterstore destination numkeys key [key ...] [weights weight[weight ...]] [aggregate <sum | min | max>] |
zunionstore destination numkeys key [key ...] [weights weight[weight ...]] [aggregate <sum | min | max>] |
2.8 zadd key score member [score member ...]
Add or update specified elements with associated scores in a sorted set. Scores must be of type double. +inf and -inf are also valid as extreme limits.
Options for ZADD:
XX: Only updates existing elements; does not add new ones.
NX: Only adds new elements; does not update existing ones.
CH: Includes the count of updated elements (default is the count of added elements).
INCR: Increments the score of the element by the specified value, similar to
zincrby
. Only one element and score can be specified.
Syntax:zadd key [NX | XX] [GT | LT] [CH] [INCR] score member [score member ...]
2.9 Difference Between Lists, Sets, and Sorted Sets
Data Structure | Allows Duplicate Elements | Ordered | Order Basis | Application Scenarios |
---|---|---|---|---|
List | Yes | Yes | Index | Timeline, Message Queue, etc. |
Set | No | No | — | Tags, Social Networks, etc. |
Sorted Set | No | Yes | Score | Leaderboards, Social Networks, etc. |
3. Summary
In this article, we systematically introduced the commonly used Redis commands and their specific applications, covering the operation methods for different data types such as strings, hashes, sets, and sorted sets. At the same time, we delved into Redis's key management, expiration mechanisms, and persistence strategies, helping developers better master the core functionalities and usage scenarios of Redis. At the application level, Redis, with its efficient read/write performance, rich data structures, and flexible operation commands, has become a powerful tool for solving high concurrency and large-scale data access problems. Through these examples and analyses, we believe readers have gained a deeper understanding of Redis's use and can leverage its advantages more effectively in their projects.
4. Conclusion
Redis is not only a reflection of technology but also a tool for innovative thinking. Whether it's improving system performance or optimizing data storage and processing, Redis opens the door to more possibilities for developers. On the technological path ahead, every challenge is an opportunity for growth. By maintaining passion and focus for technology, and continuously learning and practicing, you will eventually find your own brilliance in the world of code. Just as Redis is simple yet powerful, we too can create more efficient and intelligent systems through continuous accumulation, reaching our own technological peaks. Keep it up!