[Redis] Redis general commands and key expiration strategy


Redis has many data structures, but the key types of these data structures are all string types (so, the different data structures of Redis are all for value). Because of this, there are some common commands to operate Redis for the same type of keys.

1. Basic commands

SET and GET

SET and GET can be said to be the two most basic and core commands in Redis. Redis stores data in the form of key-value pairs, so accessing data in Redis is like operating a hash table. The function of SET is to set the key and value into Redis, while GET is to take the value out of Redis through the key.

For example, the following operations:

  1. In the above operation, the SET command is used to add two key-value pairs to Redis with key key1and value 12345and key and key2value ;hello
  2. Then use a command with syntax like GET key to get the value corresponding to the key.
  3. If you use GET to obtain the value corresponding to a non-existent key, it will be returned nil(equivalent to null).

Precautions:

Through the above operations, we can find that in Redis, key and value are actually strings, but they do not need to be quoted. Of course, if you want to add it, you can use either single quotes or double quotes.

2. Global commands

Redis has many data structures, but the key types of these data structures are all string types (so, the different data structures of Redis are all for value). Because of this, there are some global commands for operating Redis corresponding to the same type of key.

KEYS

The function of the KEYS command is to query all matching keys on the current Redis server. You can use some special wildcards to describe the key pattern, and then you can query all the keys matching this pattern in Redis.

keys pattern

The schema types of KEYS given in the official documentation of Redis are as follows:


a) ?The function of the symbol is to match a character

For example: when pattern is , keys such as: , , h?llocan be matched .hellohallohxllo

b) *The function of the symbol is to match 0 or more arbitrary characters

For example: when pattern is , keys such as: , etc. h*llocan be matched .hlloheeeello

c) [ae]The meaning of the symbol only matches a or e like this

For example: when pattern is h[ae]llo, it can match hallo, hello, but not hillo.

d) [^e]The meaning of the symbol is to match non-e

For example: when pattern is h[^e]llo, it will not be found hello, but it can match other items such halloas hbllothis.

f) [a-b]The symbol means matching between a ~ b.
For example: when pattern is h[a-e]llo, it can be matched hallolike hellothis.

Notes on the KEYS command:

In the actual production environment, the command should be used with caution keys *, because this command will query all the keys currently stored in Redis, and its time complexity is O(N). If this command is used, it may have some serious consequences:

  1. Since Redis uses a single thread to process commands, if you use keys *the command, it may cause Redis to execute for a long time, and it cannot provide services to other users during this period.
  2. Redis is often used as a shield (cache) for databases like MySQL. Once keys *the data cannot be obtained from Redis (Redis blocking), a large number of other accumulated requests will time out and the data will be queried from the database. At this time, databases like MySQL You may be caught off guard, which is very likely to cause the database to crash.

EXISTS

The function of the exists command is to determine whether a certain key exists. Returns 1 if it exists, 0 if it does not exist.

Its syntax format is:

exists key [key ...]

This means that the exists command can query a key alone or multiple keys at the same time:

Notes on using the EXISTS command:

  • The time complexity of Redis querying whether a certain key exists is O(1), because Redis organizes these keys in a data structure such as a hash table.
  • Although the time complexity of Redis querying whether a certain key exists is O(1), because Redis processes commands in a single thread, and the Redis client and server communicate through the network, multiple keys can be queried at the same time. The efficiency is much higher than when querying individual keys separately.

OF THE

The function of the DEL command is to delete the specified key. It returns 1 if the deletion is successful and 0 if it fails.
Usage syntax:

del key [key ...]


Like the EXISTS command, the time complexity of executing the DEL command is also O(1). You can delete a single key or delete multiple keys at the same time, but please note that multiple keys should be deleted at the same time to avoid affecting the performance of Redis.

EXPIRE and TTL

The EXPIRE command is used to specify a second-level expiration time for the key. Of course, there is also a command PEXPIER, which specifies an expiration time at the millisecond level. When the key expires, the key will be deleted. The function of the TTL command is to obtain the remaining expiration time of a certain key. If the expiration time is not set, it will return - 1, and if it has timed out, it will return - 2.

EXPIRE usage syntax:

expire key seconds

TTL usage syntax:

ttl key

Example of use:

Classic interview question: How is the key expiration strategy implemented in Redis?

As shown in the figure below, it shows the entire process of setting a timeout period for a key and then expiration:

In the actual production environment, Redis has a large number of keys, and most of the keys have a timeout period set. For Redis, memory space is an extremely precious resource. If expired keys are not cleaned up in time, a lot of memory space will be wasted.

So how to clean up these keys that may expire at any time?

Maybe you will think of finding expired keys in all keys regularly and clearing them. At first glance, it seems very simple to implement, but don’t forget that Redis uses multi-threading to process tasks. If you use it in this way If you clean up the key, the life cycle of Redis will have ended long ago.

In fact, simply speaking, the expiration strategy of keys in Redis is 定期删除与惰性删除a combination of:

1. Delete regularly

Periodic deletion is an active expiration checking mechanism in Redis.

Redis periodically (default 10 times per second, can be adjusted in the configuration file) randomly selects some keys that have an expiration time set and checks whether their expiration time has expired. If the key has expired, Redis will delete it.

Moreover, Redis will randomly select a part of keys to check and clean every time it performs a regular deletion operation . This is done to spread out the performance impact of periodic delete operations so that a large number of expired keys are not deleted at one time .

2. Lazy deletion

Lazy deletion is a passive expiration checking mechanism in Redis.

When a client attempts to read the value of a key, Redis first checks the expiration time of the key. If a key has expired, Redis does not return its value but deletes it immediately. Lazy deletion ensures that when a key is accessed, it is deleted immediately if it has expired. This reduces the likelihood of expired keys accumulating in memory.

Using these two methods together, Redis implements an efficient key expiration strategy, but there may still be situations where some expired keys are not cleaned up in time, especially when a large number of expired keys accumulate. In order to ensure timely cleaning of expired keys, you can also consider the following methods:

  • Set appropriate expiration time: In the configuration file, set a reasonable expiration time for keys to ensure that a large number of expired keys do not accumulate in memory.

  • Use memory elimination strategies: Redis provides different memory elimination strategies, such as LRU (least recently used), LFU (least frequently used), etc. By choosing an appropriate retirement strategy, some keys, including expired keys, can be proactively deleted when memory is low.

  • Periodic scanning and cleaning: Custom scripts or tasks can be executed periodically to scan and clean expired keys. This ensures that even if the main Redis thread is busy, there is a separate task responsible for cleaning up expired keys.

  • Use the Pub/Sub function of Redis: You can use the publish/subscribe function of Redis to implement an expired key monitoring system. When a key expires, Redis can publish a message, which can then be processed by subscribers to perform cleanup operations.

The combined use of these methods can ensure that expired keys in Redis are cleaned up in a timely manner, thereby maintaining memory stability and performance.

TYPE

The function of the TYPE command is to return the data type of the value corresponding to the specified key.
Its syntax is:

type key

For example:

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/132737195