Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Keys in the Redis command

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces how to use Keys in the Redis command, the content is very detailed, interested friends can refer to, hope to be helpful to you.

DEL

Deletes the specified key-value pair, or ignores it if the specified key does not exist. The time complexity of the DEL command is O (N). For other data types except strings, the time complexity of the command is O (M), where M is the number of elements of the value. Therefore, try to avoid deleting too many complex data types at once in the production environment.

127.0.1 zhe 6379 > SET key1 "jackey" OK127.0.0.1:6379 > SET key2 "zhe" OK127.0.0.1:6379 > DEL key1 key2 key3 (integer) 2

DUMP

The earliest available version 2.6.0

Serializes the value stored by the specified key using a Redis format. You can deserialize this value using the RESTORE command.

This serialization format has the following three characteristics:

It contains a 64-bit checksum for error checking, and the RESTORE command checks the checksum before deserialization

The encoding format of value is the same as that of RDB file

Versions of RDB are serialized into values, so different versions of Redis may reject deserialization because they are not compatible with RDB versions

The serialized value does not contain information about the expiration time, and you can use the PTTL command to get the survival time of the current value. Nil is returned if the value does not exist

127.0.0.1 SET key1 "jackey" OK127.0.0.1:6379 > DUMP key1 "\ X00\ x06jackey\ b\ xec\ x89'G'X\ xfc:" 127.0.0.1 OK127.0.0.1:6379 > DUMP not-exist-key (nil)

The time complexity of DUMP is divided into two parts: the time complexity of accessing key value is O (1), while the time complexity of serialization value is O (NumberM), N is the number of elements that make up the value, and M is the average size of the element. If you serialize a shorter string, the time complexity of the command can be seen as O (1).

EXISTS

The earliest available version 1.0.0

It is used to determine whether key exists. Multiple parameters are supported after version 3.0.3, that is, multiple key can be determined at one time, and the return value is the number of key that exists. For determining whether a single key exists, a 1 or 0 is returned, so the command is backward compatible.

It is important to note that if there is a duplicate command in the parameter, the returned result will not be duplicated.

127.0.0.1 OK127.0.0.1:6379 > SET key1 "jackey" OK127.0.0.1:6379 > SET key2 "zhe" OK127.0.0.1:6379 > EXISTS key1 (integer) 1127.0.0.1 > EXISTS not-exist-key (integer) 0127.0.0.1 > EXISTS key1 key2 not-exist-key (integer) 2127.0.0.1 > EXISTS key1 key1 key1 (integer) 3

EXPIRE

The earliest available version 1.0.0

Sets the time to live for the specified key. The time to live will be deleted or overwritten by DEL,SET,GETSET and all STORE commands. If we only change the value of key without changing the time to live or save it to a new key, the survival time of the original key remains the same. If you rename a key using RENAME, the lifetime of the original key is assigned to the new key.

If you want to clear the time to live and make the specified key a permanent key, you can use the PERSIST command, which we'll cover in more detail later.

If you use EXPIRE/PEXPIRE to set a non-positive time to live for a key, or if you set a past time using EXPIREAT/PEXPIREAT, the key will be deleted directly.

127.0.0.1 EXPIRE key1 6379 > EXISTS key1 (integer) 0

If you use EXPIRE to set the survival time for a key that already has a survival time, the survival time of the key will be updated, which we will use in many applications.

Note: prior to version 2.1.3 of Redis, if you changed the value of a key with time to live, the entire key would be deleted.

With regard to time precision, in the Redis2.4 version, a key is still accessible within a second after it expires, while in version 2.6, the time has been accurate to 1 millisecond. Because since version 2.6, survival time is saved in absolute time (Unix timestamp), which means that your computer's time needs to be reliable. If you load the RDB file on another machine, when the time gap between the two machines is large, you will find that some key may be deleted or some key survival time will be extended.

Let's talk about how Redis makes key expire. Redis has two expiration strategies: one is passive and the other is active.

Passive expiration means that when a client accesses a key, the server checks the survival time of the key to determine whether it expires. Of course, there is a problem with this expiration strategy. If a key is not accessed all the time, it will not be found to have expired, and it will always be "alive" in memory. So Redis will regularly and randomly check the key with a set survival time to see if they are out of date, and if they are out of date, they will be cleaned up in time. Redis does the following 10 times per second:

Randomly view 20 key whose survival time has been set (from the set that set the survival time)

Delete all expired key

If the expired key exceeds 25%, it will be executed again from the first step.

EXPIREAT

The earliest available version 1.2.0

This command works the same as EXPIRE, except that its parameters require a Unix timestamp (that is, the number of milliseconds since January 1, 1970).

127.0.0.1 GET key2 "zhe" 127.0.0.1 EXPIREAT key2 1537733374 (integer) 1127.0.1 EXPIREAT key2 6379 > TTL key2 (integer) 12960

KEYS

The earliest available version 1.0.0

This command returns all matching key with a time complexity of O (N). On entry-level laptops, it only takes 40 milliseconds for Redis to scan 1 million key, but we still need to avoid using this command in a production environment, according to official documents. In particular, do not use commands such as KEYS *, because you do not know how many key exist in the production environment, which may make the Redis of your production environment unavailable for a long time. So, please delete the KEYS command in the application layer code immediately or take the time to update your resume.

If you need to find key, you can use the SCAN command or the sets command.

Although the KEYS command is highly deprecated, its matching strategy should be introduced:

? Is a wildcard for a single character, * is a wildcard for any number of characters, [ae] matches to an or e, ^ e means it doesn't match ememary an or b or c, and special symbols are separated by\.

127.0.0.1 key1hello 6379 > MSET key1hello jackey key2hello zhe age 3OK127.0.0.1:6379 > KEYS key?hello1) "key1hello" 2) "key2hello" 127.0.0.1 KEYS 6379 >) "key1hello" 2) "key2hello" 127.0.0.1 KEYS 6379 > KEYS * age*1) "age" 127.0.0.1 > KEYS * 1) "age" 2) "key1hello" 3) "key2hello"

MIGRATE

The earliest available version 2.6.0

This command is used to transfer the key of the source instance to the target instance by atomic operation, and then delete the key of the source instance. It is equivalent to performing a DUMP+DEL operation on the source instance and a RESTORE operation on the target instance. This action blocks two instances of the transfer, and the key always exists in one instance during the transfer, unless a timeout error occurs. After version 3.2, MIGRATE can transfer multiple key as pipelines at once.

When you execute the MIGRATE command, you must set a timeout, and if the timeout command is not finished, an IOERR will be thrown. However, when this error is returned, there may be two states for both instances: either the specified key exists for both instances, or only the specified key exists for the source instance. In short, key will not be lost.

Since version 3.0.6, MIGRATE supports transmitting more than one key at a time. In order to ensure no overload or ring operation, MIGRATE needs to use the KEYS parameter, while the originally specified key parameter should be set to an empty string.

MIGRATE 192.168.1.34 6379 "" 0 5000 KEYS key1 key2 key3

There are two optional parameters to be introduced: one is COPY. If this parameter is added, the key in the source instance will not be deleted after the transfer is completed. The other is REPLACE, which replaces the key that already exists in the target instance. These two parameters are not available until version 3.0.

MOVE

The earliest available version 1.0.0

I don't know if you remember the SELECT command we mentioned earlier, which SELECT is used to switch databases. Using the MOVE command moves the key of the current database to the specified database, and does nothing if the key already exists in the specified library or if the key does not exist in the current library.

127.0.0.1) KEYS * 1) "age" 2) "key1hello" 3) "key2hello" 127.0.0.1 > MOVE age 1 (integer) 1127.0.0.1 > KEYS * 1) "key1hello" 2) "key2hello" 127.0.0.1 > SELECT 1OK127.0.0.1:6379 [1] > KEYS * 1) "age"

OBJECT

The earliest available version 2.2.3

OBJECT is used to view relevant information inside a Redis object. This command is often used when debugging. Let's introduce the specific use of the OBJECT command:

OBJECT REFCOUNT key: returns the number of references to the value of the specified key

OBJECT ENCODING key: returns the encoding format used by the internal storage of the specified key

OBJECT IDLETIME key: returns the idle time of the specified key (how long it has not been read or written). Currently, the minimum precision is 10 seconds. This command is often used in the Redis phase-out mechanism (the elimination strategy is LRU or noeviction)

OBJECT FREQ key: returns the logarithm of the specified key access frequency, which is used when the elimination policy is LFU

OBJECT HELP: return help information

There are also many encoding formats for objects:

Strings will be encoded as raw or int

Lists will be encoded as ziplist or linkedlist

Sets will be encoded as intset or hashtable

Hashs will be encoded as ziplist or hashtable

Sorted Sets will be encoded as ziplist or skiplist

127.0.0.1 OBJECT IDLETIME key2hello 6379 > OBJECT REFCOUNT key1hello (integer) 1127.0.0.1 OBJECT IDLETIME key2hello 6379 > OBJECT ENCODING age "int"

PERSIST

The earliest available version 2.2.0

Deletes the expiration time of the specified key, making it a permanent key.

PEXPIRE

The earliest available version 2.6.0

PEXPIRE does the same thing as EXPIRE, except that the unit of time in the parameter is millisecond.

PEXPIREAT

The earliest available version 2.6.0

The effect is the same as EXPIREAT, and the parameter is also millisecond.

PTTL

The earliest available version 2.6.0

Returns the number of milliseconds of remaining time to live for the specified key. The return value for versions later than 2.8varies somewhat, returning-2 if key does not exist, or-1 if key is permanent.

RANDOMKEY

The earliest available version 1.0.0

This command is used to return a random key from the current database.

RENAME

The earliest available version 1.0.0

Rename a key. If key does not exist, an error is returned. If the new key already exists, this command overwrites the original key (it actually executes an implicit DEL command, so the deletion latency is high if the objects stored by the original key are large). Prior to version 3.2, an error was reported if the source key and destination key were the same.

RENAMENX

Rename the key if the new key does not exist, return 0 if it exists, and 1 successfully.

RESTORE

The earliest available version 2.6.0

Usage: RESTORE key ttl serialized-value [REPLACE]

This command deserializes a set of data and resides it to key. If ttl is 0, then key is permanent. After the Redis3.0 version, if the REPLACE parameter is not used and key already exists, an error "Target key name is busy" is returned.

SCAN

The earliest available version 2.8.0

Usage: SCAN cursor MATCH pattern COUNT count

Where cursor is a cursor and MATCH and COUNT are optional parameters.

The SCAN command and the SSCAN, HSCAN, and ZSCAN commands are used for an incremental set of iterated elements, which returns a small portion of data each time and does not block Redis as KEYS does. The SCAN command is cursor-based and returns a cursor for the next iteration after each call. When the cursor returns 0, the iteration ends.

The number of SCAN returns each time is not fixed, or it is possible that the returned data is empty. In addition, the SCAN command supports matching as well as the KEYS command.

We put 10000 key in Redis for testing.

The results are as follows:

127.0.0.1 scan 0 match key24* count 10001) "1688" 2) 1) "key2411" 2) "key2475" 3) "key2494" 4) "key2406" 5) "key2478" 127.0.0.1 key2494 "10001)" 2444 "2) 1)" key2458 "2)" key249 "3)" key2407 "4)" key2434 "5)" key241 "6)" key2497 "7)" key2435 "8) "key2413" 9) "key2421" 10) "key248" 127.0.0.1 match key24* count 6379 > scan 2444 match key24* count 10001) "818" 2) 1) "key2459" 2) "key2462" 3) "key2409" 4) "key2454" 5) "key2431" 6) "key2423" 7) "key2476" 8) "key2428" 9) "key2493" 10) "key2420" 127.0.1 scan match key24* count 10001) "9190" 2) 1) "key2402" 2) "key2415" 3) "key2429" 4) "key2424" 5) "key2425" 6) "key2400" 7) "key2472" 8) "key2479" 9) "key2448" 10) "key245" 11) "key2487" 12) "key2430" 13) "key2405" 127.0.0.1key2429 6379 > scan 9190 match key24* count 10001) "12161" 2) 1) "key2488" 2) "key2437" 3) "key2404" "4)" key2440 "5)" key2461 "6)" key2416 "7)" key2436 "8)" key2403 "9)" key2460 "10)" key2452 "11)" key2449 "12)" key2482 "127.0.0.1 match key24* count 6379 > scan 12161 match key24* count 10001)" 11993 "2) 1)" key2483 "2)" key2491 "3)" key242 "4)" key2466 "5)" key2446 "6)" key2465 "7)" key243 " 8) "key2438" 9) "key2457" 10) "key246" 11) "key2422" 12) "key2418" 127.0.0.1 key2418 6379 > scan 11993 match key24* count 10001) "7853" 2) 1) "key2498" 2) "key2451" 3) "key2439" 4) "key2495" 5) "key2408" 6) "key2410" 127.0.0.16379 > scan 7853 match key24* count 10001) "5875" 2) 1) "key2486" 2) "key2490" 3) "key244" 4) "key2401" 5) "key2463" 6) "key2481" 7) "key2477" 8) "key2468" 9) "key2433" 10) "key2489" 11) "key2455" 12) "key2426" 13) "key24" 14) "key2450" 15) "key2414" 16) "key2442" 17) "key2473" 18) "key2467" 19) "key2469" 20) "key2456" 127.0.0.1: 6379 > scan 5875 match key24* count 10001) "14311" 2) "key2492" 3) "key2480" 4) "key2427" 5) "key2443" 6) "key2417" 7) "key2432" 8) "key240" 9) "key2445" 10) "key2484" 11) "key2444" 12) "key247" 13) "key2485" 127.0.0.1 match key24* count 13379 > scan 14311 match key24* count 10001) "16383" 2) 1) " Key2441 "2)" key2474 "3)" key2447 "4)" key2471 "5)" key2470 "6)" key2464 "7)" key2412 "8)" key2419 "9)" key2499 "10)" key2496 "127.0.1) scan 16383 match key24* count 10001)" 0 "2) (empty list or set)

You can see that although we set the count to 1000, Redis returns only about 10 values at a time.

SORT

The earliest available version 1.0.0

When there are N elements to sort and M elements are returned, the time complexity of the SORT command is O (N+M*log (M)).

This command is used to return or save keys for list,set and sorted set. By default, numbers or sortable key are sorted, and Redis treats them as double-precision floating-point numbers.

If you want to sort the strings in lexicographical order, you can use the ALPHA parameter.

If you want to sort by external field, you can use the BY parameter.

TOUCH

Earliest available version 3.2.1

Modify the last access time of one or more key, if the key does not exist, ignore it.

TTL

The earliest available version 1.0.0

Returns the remaining time in seconds of the specified key.

In version 2.6 or earlier,-1 is returned if key does not exist or is a permanent key. Starting with version 2. 8, return-2 if key does not exist and-1 if key is permanent key.

TYPE

The earliest available version 1.0.0

Returns the type of value stored by key. The types are the 5 data types we described in the article Redis basic data structures.

String

String is the most basic and most commonly used type. It is binary safe, that is, we can serialize the object into a json string and store it in Redis as a value. When allocating memory, Redis allocates some redundant space for a string to avoid frequent memory allocation operations due to changes in the value of the string. When the string length is less than 1m, the existing space will be doubled for each expansion. When the length is greater than 1m, the maximum length of the 1m Magi Redis string will be 512m.

Hash

Hash is a collection of key-value pairs, which is equivalent to HashMap in Java. The actual structure, like HashMap, is the structure of array + linked list. The difference is that the expansion method is different. HashMap performs a rehash, while Redis creates a new array in order not to block the service. When querying, it will query both Hash, and then gradually transfer the old Hash content to the new one. A Hash can store up to 232-1 key-value pairs.

List

List is equivalent to LinkedList in Java. The time complexity of insert and delete operation is O (1), while the time complexity of query operation is O (n). We can use List's rpush, rpop, lpush, and lpop commands to build queues or stacks. The list can store up to 232-1 elements.

Set

Set is an unordered set of String type, and the element is unique, which is equivalent to HashSet in Java. The time complexity of its insert, delete and query operations is all O (1). The maximum number of elements is also 232-1.

Zset

Zset can be seen as a combination of SortedSet and HashMap in Java. On the one hand, it does not allow elements to repeat, on the other hand, it sorts each element through score.

UNLINK

The earliest available version 4.0.0

This command, similar to DEL, deletes the specified key. The difference is that the time complexity of this command is O (1). It first removes the key from the keyspace, when the specified key has been deleted, but the memory has not been freed. Therefore, this command frees memory in another thread. The operation time complexity of this step is O (N).

WAIT

The earliest available version 3.0.0

This command blocks the client until all previous writes are completed and the specified number of copies are saved. The command always returns the number of copies or timeout.

On how to use Keys in the Redis command to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report