Redis base data types
Sting Type:
The Redis string is a dynamic string, a string that can be modified, and the internal structure implements a Java-like ArrayList that uses a pre-allocated redundancy space to reduce the frequent allocation of memory, as shown in the interior for the actual space allocated for the current string capacity Generally higher than the actual string length len. When the string length is less than 1M, the expansion is doubled the existing space, if more than 1M, the expansion will only be more than 1M of space. It is important to note that the maximum string length is 512M.
Operation Command:
Set key value
Get key
Exists key
Del key
Batch Setup
Mset key1 value1 key2 value2 Key3 value3
Mget Key1 Key2 Key3
Expiration settings
Expire Key1 expires after 5 5 seconds
Setex Key 5 value expires after #5s, equivalent to Set+expire
Setnx key Value No key returned 1 set successfully, key already exists return 0
Count
INCR Key # Increments the value of key by 1, incrementing the error if it exceeds the maximum value (Incrby age 5 increments by 5)
List type:
The Redis list is equivalent to the LinkedList in the Java language, noting that it is a linked list rather than an array. This means that the INSERT and delete operations of the list are very fast and the time complexity is O (1), but the index positioning is slow and the time complexity is O (n), which is surprising.
When the list pops up the last element, the data structure is automatically deleted and the memory is recycled.
Operation Command:
Rpush key value1 value2 value3 storage element value1 on the far left
Llen Key Query list length
Lpop key takes the value of the corresponding key from the left, and it is not removed (right-hand-left-side-out: queue)
Rpop key to the right of the value of the corresponding key, out of the left (right into the right side: stack)
Slow operation
Lindex is equivalent to the Get (int index) method of the Java list, which needs to traverse the linked list, and the performance will become worse as the index of the parameter increases.
The index can be a negative number, index=-1 represents the penultimate element, and the same index=-2 represents the second-to-last element.
Lindex Key 1 Take out subscript 1, that is, put in the second element O (n) Use caution
Lrange Key 0-1 # Get all elements, O (n) with caution
LTrim key 1-1 Clears the list LTrim key 1 0 to intercept subscript 11 until the end if the interval is negative
Quick List
First, in the case of fewer list elements, a contiguous memory store is used, which is ziplist, which is the compression list. It stores all the elements next to each other, allocating a contiguous amount of memory. When the amount of data is more than the time will be changed to quicklist. Because the additional pointer space required by the normal list is too large, it can be a waste of space and will aggravate the fragmentation of the memory. For example, this list only contains data of type int, and the structure requires two additional pointers prev and next. So Redis combines lists and ziplist to form a quicklist. That is, multiple ziplist are used with two-way pointer strings.
Hash (dictionary): Array + list Two-dimensional structure value can only be a string
Java HashMap when the dictionary is large, rehash is a time-consuming operation that requires all rehash at once. For high performance, Redis does not clog services, so it adopts a progressive rehash strategy. Progressive rehash will keep the old and new two hash structures at the same time, the query will query two hash structures at the same time, then in the subsequent scheduled tasks and the hash operation instruction, the old hash content is moved to the new hash structure in a little step. When the relocation is complete, the new hash structure will be used instead.
Hash can store a structure part of the field data, such as a string type of data if the entire structure of the serialization of storage causes network traffic waste. Hash also has drawbacks. Storage consumption is greater than a single string. According to the actual situation to choose hash or string to store
Operation Command:
Hset Books Java "Think in Java" # command line string if it contains spaces, enclose it in quotation marks if the update operation is directly overwritten
Hget Books Java
Hgetall Books
Batch Set
Hmset Books java "Effective Java" python "Learning python" Golang "Modern Golang Programming"
Count
Hincrby User-laoqian Age 1
Application: Storing Data Objects
Set Type: (collection)
The collection of Redis is equivalent to the HashSet inside the Java language, and its internal key-value pairs are unordered and unique. Its internal implementation is equivalent to a special dictionary, and all value in the dictionary is a value of NULL. When the last element in the collection is removed, the data structure is automatically deleted and the memory is recycled.
Operation Command:
Sadd key value successfully returned 1 failed return 0
Sadd Key value1 value2 successfully returned 2 failed to return 0
Smembers Key # Note the order, and the insertion is not consistent, because set is unordered to isolate all
Sismember Key Value # query If a value exists, equivalent to contains (O) exists return 1 does not exist return 0
SCard Books # Gets the length equivalent to count ()
Spop Books # pops up a random
The application set structure can be used to store the user ID of the event winning, because there is a go-to function, you can guarantee that the same user will not win two times.
Zset type: (with sequence list)
The Zset internal sorting function is implemented by the "Jump List" data structure, which is very special and complex.
Operation Command:
Zadd key score value sorted by score
Zrange Key 0-1 # Listed by score, parameter range is all taken out
Zrevrange Key 0-1 # by score inverse sequence, parameter interval is the rank range
Zcard Key # Gets the length equivalent to count ()
Zscore Key value # Gets the score # of the specified value internal score is stored using a double type, so there is a decimal point accuracy problem
Zrank Key Value # ranking
Zrangebyscore key 0 8.91 # Traverse Zset based on the score interval
Zrangebyscore books-inf 8.91 Withscores # traverses-∞ based on the score interval (Zset, 8.91) and returns the score. INF stands for infinite, infinity meaning.
Zrem Key Value # Delete value
Application: Zset can be used to save the fan list, value is the fan user Id,score is the focus time. We can sort the fan list by the time of attention.
Zset can also be used to store student scores, value is the student's id,score is his exam results. We can sort the scores by fractions to get his rank.
General rules for container-type data structures:
List/set/hash/zset these four types of data structures are container-type data structures that share the following two general rules:
Create if not exists
If the container does not exist, create one, and then proceed. For example, if the Rpush operation is not listed at first, Redis will automatically create one and then rpush into the new element.
Drop if no elements
If the element in the container is not there, delete the element immediately and release the memory. This means that the lpop operation to the last element, the list disappears.
Expiry time:
All REDIS data structures can be set to expire time, and Redis will automatically delete the corresponding objects. It is important to note that the expiration is in object units, such as the expiration of a hash structure that is the expiration of the entire hash object, not one of its child keys.
Another important point to note is that if a string has already been set to expire, and then you call the Set method to modify it, its expiration time disappears.