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

Example Analysis of basic types and usage of redis

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

This article mainly introduces the example analysis of the basic types and usage of redis, which is very detailed and has a certain reference value. Friends who are interested must finish it!

The basic types of data stored in redis are: string (string type), hash (hash type), list (list type), set (collection type), and zset (ordered collection type).

Do some exercises in turn. The redis command is not case sensitive.

Key related operation 127.0.0.1 OK127.0.0.1:6379 # set key hello # # set OK127.0.0.1:6379 > set key1 worldOK127.0.0.1:6379 > keys ke* # # keys query key name 1) "key1" 2) "key" 127.0.0.1 OK127.0.0.1:6379 6379 > del key1 # # Delete key-value pair (integer) 1127.0.1 OK127.0.0.1:6379 6379 > exists key # # query whether the key name exists (integer) 1 # exists returns 1127. 0.0.1 exists key1 6379 > exists key1 (integer) 0 # # there is no type that returns 0127.0.0.1 type key # # query key type string string type 127.0.0.1type key 6379 > exists num (integer) 0127.0.0.1type key 6379 > incr num # # incr a value that does not exist First create a new value, assign it to 0, and then increase it by 1. Yard operation. Corresponding to decr (integer) 1127.0.0.1 incr key 6379 > set key helloOK127.0.0.1:6379 > incr key # # cannot increase the specified value for string self-increment (error) ERR value is not an integer or out of range127.0.0.1:6379 > incrby num 3 # # increby Corresponding to decrby (integer) 4127.0.0.1 incrbyfloat num 6379 > strlen 0.7 # # increase the floating point number "4.7" 127.0.0.1 incrbyfloat num 6379 > append key "world!" # # append append character (integer) 12127.0.0.1 strlen 6379 > get key "hello world!" 127.0.0.1 incrbyfloat num string length (integer) 12127.0.1 strlen string length (integer) 12127.0.0.1 integer > mget key num # mget batch get key 1 ) "hello world!" 2) "4.7" 127.0.0.1 mset 6379 > mset key hi num 5.5 # # mset batch setting OK127.0.0.1:6379 > mget key num1) "hi" 2) "5.5" 127.0.1 mset 6379 > set foo bar OK127.0.0.1:6379 > getbit foo 1 # # getbit get a bit binary value (integer) 1127.0.0.1 mset 6379 > setbit foo 22 0 # # setting Modified bit value (integer) 1127.0.0.1 bap 6379 > get foo # # modified successfully "bap" 127.0.0.1 bap > set foo barOK127.0.0.1:6379 > set foo1 aarOK127.0.0.1:6379 > bitop or result foo foo1 # # bitop bit Operation (integer) 3127.0.1 bap > get result "car"

GETBIT key offset

SETBIT key offset value

BITCOUNT key [start] [end] gets the number of binary bits with a value of 1 in the key value, and start and end represent byte positions

BITOP operation destkey key [key...] Bit operations are performed on a plurality of key values, and the results are stored in the corresponding key values of the destkey. Supported operations: AND, OR, XOR, NOT.

GETSET key newValue atomic operation, set the new value, and return the original value. Returns nil if the original value does not exist.

SETEX key seconds value sets the expiration time of key-value pairs to seconds seconds.

SETNX key value put if absent, or do nothing .

SETRANGE key offset value replaces length (value) characters with value from the position where index equals offset. If the offset is out of range, the 0x00 is added in the middle.

GETRANGE key start end gets the specified returned string with a closed interval. If end exceeds the length, it is fetched to the end of the string.

MGET key [key...]

MSET key value [key value...]

MSETNX key value [key value...] atomic operation. If any Key already exists in this batch of Keys, the operation will all be rolled back, that is, none of the changes will take effect. 1 means all settings are successful; 0 means none are set.

127.0.0.1 getset foo hi # # set the new value and return the old value nil (nil) 127.0.0.1 nil 6379 > get foo "hi" 127.0.0.1 nil 6379 > setex foo 2 hello # # set the key value pair. If OK127.0.0.1:6379 > get foo # # does not expire in 2 seconds, the return value "hello" 127.0.0.1 nil 6379 > get foo # # will be returned after the expiration Return nil (nil) 127.0.0.1 appy 6379 > set foo helloOK127.0.0.1:6379 > setrange foo 1 appy # # string after replacing index=1 (integer) 5127.0.0.1 ee 6379 > get foo "happy" 127.0.0.1 ee (integer) 5 # # return the modified length 127.0.0.1 ee 6379 > get foo # # replace two characters "heepy" 127.0.0.1 ee 6379 > setrange foo 8 day (integer) 11 127.0.0.1 heepy 6379 > get foo "heepy\ x00\ x00\ x00day" 127.0.0.1 heepy 6379 > get bar (nil) 127.0.0.1 heepy 6379 > setrange bar 2 ee # # bar is nil Add two 0x00 (integer) 4127.0.0.1 x00ee 6379 > get bar "\ X00\ x00ee" 127.0.0.1 x00ee 6379 > set key1 helloOK127.0.0.1:6379 > msetnx key1 hi key2 hi # # key2 does not exist, do not modify (integer) 0127.0.1 nil1 > mget key1 key2 # # key2 is still nil1) "hello" 2) (nil) hash

HSET key field value

HGET key field

HMSET key field value [field value...]

HMGET key field [field...]

HGETALL key

HEXISTS key field

Assignment when the HSETNX key field value field does not exist. Unlike the HSET type, the difference is that HSETNX does nothing if the field exists.

HINCRBY key filed increment if key and field do not exist, it is automatically created. The key value is 0, and then the value is added.

HDEL key field [field...] This is deleted is key:field, you cannot delete key directly. If you want to delete key, use the DEL command.

HEYS key only gets the field name

HVALS key only gets field values

HLEN key gets the number of fields

127.0.0.1 tom hanmeimei 004OK127.0.0.1:6379 > HGETALL g1class11) "xiaoming" 2) "001" 3) "xiaohong" 4) "002" 5) "tom" 6) "003" 7) "hanmeimei" 8) "004" 127.0.1 tom 6379 > HKEYS g1class11) "xiaoming" 2) "xiaohong" 3) "tom" 4) "hanmeimei" 127.0.1 When HLEN g1class1 (integer) 4127.0.0.1 het 6379 > HGET g1class1 xiaohong "002" 127.0.0.1 het new value When 1 (integer) 1127.0.0.1 hset 6379 > hset g1class1 xiaohong 007 # # hset update value is returned, 0 (integer) 0127.0.1 hset 6379 > hsetnx g1class1 tom 008 # # existing value is returned, and the existing value of (integer) 0127.0.0.1 hset 6379 > hget g1class1 tom # # is not operated. The update does not take effect. Still 003 "003" 127.0.0.1 ERR wrong number of arguments for 6379 > hdel g1class1 # # cannot delete key (error) ERR wrong number of arguments for 'hdel' command127.0.0.1:6379 > DEL g1class1 # # use DEL to delete key (integer) 1127.0.0.1 ERR wrong number of arguments for 6379 > hgetall g1class1 # # query is empty list or set

Used to store hierarchical data. The external key, as the prefix, is used as the key in the first-level key,hash as the second-level key.

Store objects that contain multiple attributes, such as the various attributes of a blog: title, tag, classification, etc. Modify a property without having to manipulate the entire blog content.

List

Redis list types are implemented internally using bi-directional lists, so you can add / remove elements to / from both ends.

LPUSH key value [value...] Add an element from the left, initialize an empty list if key does not exist, and then add it. Returns the number of linked lists after insertion.

LPUSHX key value inserts Value on the left side of the list only if the specified Key exists, otherwise nothing will happen. Returns the number of linked lists after insertion.

RPUSH key value [value...] Add elements from the right

RPUSHX key value inserts Value on the right side of the list only if the specified Key exists, otherwise nothing will happen. Returns the number of linked lists after insertion.

LPOP key pops elements from both ends

RPOP key

LLEN key gets the number of elements in the list

LRANGE key start end gets the list snippet, with the left first and the right behind. The starting index is 0, the rightmost element index can be-1, the second index on the right can be-2, and so on. The index is from left to right, and if start is to the right than end, an empty list is returned. The end value can be greater than the length range.

LREM key count value starts on the left (count > 0) and deletes the elements whose previous count value is value; from the right (count)

< 0)开始,删除前|count|个值为value的元素 ; 删除所有值为value的元素(count = 0)。返回实际删除元素的个数。 LINDEX key index 获取指定索引的元素值 LSET key index value 设置指定索引的元素值 LTRIM key start end 删除指定索引范围之外的所有元素。start和end的规则与lrange的相同。 LINSERT key BEFORE|AFTER pivot value 从左到右查找pivot,将value插在其前面(BEFORE)或者后面(AFTER)。 返回插入后,元素总个数。 RPOPLPUSH source destination 删除source最右边的元素,插入到destination最左边。返回操作的元素。 127.0.0.1:6379>

Lpush num 12 # # first push 1, then push 2 (integer) 2127.0.0.1 push 6379 > rpush num 3 4 # # first push 3, then push 4 (integer) 4127.0.0.1 push 6379 > lrange num 0-1 # # starting from 0, it shows 4 elements 1) "2" 2) "1" 3) "3" 4) "4" 127.0.1 integer 6379 > llen num (integer) 4127.0.0.1 integer 6379 > lrange num-1-2 # # start than end to the right Return empty list (empty list or set) 127.0.0.1 lpush num 6379 > lpush num-2-1 # # from second right to first right) "3" 2) "4" 127.0.1) > lrange num 3 43 (integer) 7127.0.1) 6379 > lrange num 0-11) "3" 2) "4" 3) "3" 4) "2" 5) "1" 6) "3" 7) " 4 "127.0.0.1 lrem num 6379 > lrange num 2 3 (lrange num 0-11)" 4 "2)" 2 "3)" 1 "4) 3)" 3 "5) 4" 127.0.0.1 lrange num 6379 > 127.0.1 lrange num 6379 > lrange num 0 4 # deleted all values of 4 elements (integer) 2 # Two 127.0.0.1lpush num 6379 > lrange num 0-11) "2" 2) "1" 3) "3" 127.0.0.1 lpush num 6379 > lrange num 2 3 (integer) 1 # # only one element 127.0.0.16379 > lrange num 0-11) "2" 2) is deleted. Enter the front of the first 1 on the left (integer) 5 # # after insertion There are 5 elements: 127.0.0.1 lrange num 0-11) "3" 2) "4" 3) "1" 4) "2" 5) "1" 127.0.0.1 lrange num1 6379 > rpoplpush num num1 # # transfer an element "1" 127.0.0.1 lrange num1 0-11) "1" 127.0.0.1 lrange num1 0-11) "1" 127.0.0.1 lrange num1 6379 > rpoplpush num num1 "2" 127.0.1 11) "2" 2) "1" 127.0.0.1 lpushx num 6379 > lrange num 0-1 # # num transferred 2 elements 1) "3" 2) "4" 3) "1" 127.0.1 lpushx num 5 # # key name num exists Push success (integer) 4127.0.0.1 push 6379 > lrange num2 0-1 (empty list or set) 127.0.0.1 lrange num2 6379 > lpushx num2 1 # # key name num2 does not exist, push failure (integer) 0127.0.1 lrange num2 6379 > lrange num2 0-1 (empty list or set) use

List page

Set

The set of redis is implemented using a hash table (hash table) with an empty value.

SADD key member [member...] Add elements that do not exist in the set; return the number of values successfully added

SREM key member [member...] deletes elements that exist in set; returns the number of successful deletions

SPOP key randomly selects an element, pops up, and returns. If key does not exist, return nil.

SMEMBERS key gets all elements

SISMEMBER key member determines whether the element is in the collection. If it exists, it returns 1 dominating key or member does not exist, and returns 0.

SCARD key gets the number of elements

SDIFF key1 [key2.] set difference set, which exists in key1 and does not exist in key2.

SINTER key [key...] sets to find the intersection.

SUNION key [key...] set union set

The SDIFFSTORE destination key1 [key2...] collection finds the difference set and stores it in destination.

The SINTERSTORE destination key [key...] collection finds the intersection and stores it in destination.

The SUNIONSTORE destination key [key...] collection joins the union and stores it in destination.

SRANDMEMBER key [count] randomly selects count elements. When there is no parameter count, select one. Count=0, return empty list; count > 0, select min (count, scard) data, and do not repeat, return all elements at most; count

< 0 选择|count|个元素,有可能重复。 SMOVE source destination member 原子性的将参数中的成员从source键移入到destination键所关联的Set中。因此在某一时刻,该成员或者出现在source中,或者出现在destination中。如果该成员在source中并不存在,该命令将不会再执行任何操作并返回0,否则,该成员将从source移入到destination。如果此时该成员已经在destination中存在,那么该命令仅是将该成员从source中移出。如果和Key关联的Value不是Set,将返回相关的错误信息。返回1表示正常移动,0表示source中并不包含参数成员。 127.0.0.1:6379>

Sadd set1 a b # # add two nonexistent elements (integer) 2127.0.0.1 sadd set1 6379 > sadd set1 a c # # successfully add an element c (integer) 1127.0.0.1 sadd set1 6379 > smembers set1 # # get all elements 1) "c" 2) "b" 3) "a" 127.0.1 sadd set1 d # # delete an element (integer) 1127.0.1 ) "c" 2) "a" 127.0.0.1 sismember set1 6379 > sadd set1 a (integer) 1127.0.0.1 sadd set1 6379 > sadd set1 b (integer) 1127.0.0.1 sadd set1 6379 > sadd set2 ad e (integer) 3127.0.0.1 sadd set2 ad 6379 > sadd set3 c h j (integer) 3127.0.0.1vet 6379 > sdiff set1 set2 set3 # # subtraction set In set1 and not in set2 Elements in set3 1) "b" 127.0.0.1 integer > scard set1 (integer) 3127.0.1 integer > sdiffstore set4 set1 set2 set3 (integer) 1127.0.1 > smembers set41) "b" 127.0.0.1 > srandmember set1 0 (empty list or set) 127.0.1 > srandmember set1 11) "c" 127.0.1 > srandmember set1 21) "a" 2) "b" 127.0. 0.1 6379 > srandmember set1 5 # # returns min (5 3) elements, and do not repeat 1) "c" 2) "a" 3) "b" 127.0.0.1 purl 6379 > srandmember set1-5 # # returns 5 elements May repeat 1) "a" 2) "b" 3) "c" 4) "c" 5) "c" 127.0.0.1 spop set1 6379 > smembers set11 "c" 127.0.0.1 smembers set21) "d" 2) "a" 3) "e" 127.0.0.1 source 6379 > smove set2 set1 c # source does not contain moving elements Do not operate (integer) 0127.0.1 integer > smove set2 set1 e # # move one element to another set (integer) 1127.0.0.1 integer > smembers set21) "d" 2) "a" 127.0.0.1 integer > smembers set11) "b" 2) "a" 3) "e" use

A unique collection of data, such as which stores have been visited by a user.

Assemble the relevant scenes. The visiting user of each store is a set, finding the user group visiting multiple stores at the same time, finding the user group visiting a first-class store, and so on.

Sorted set

An ordered set associates a score for each element and sorts it by score. Although each element in the collection is different, their scores can be the same.

ZADD key score member [score member...] adds a new element and updates the score if the element already exists. Score supports integers and double-precision floating-point types. Returns the number of newly added elements (excluding the updated score). Inf and-inf represent positive infinity and negative infinity, respectively.

ZINCRBY key increment member increases the score of an element, and increment can be negative.

Score of the ZSCORE key member query element

ZCARD key gets the number of elements in the collection

ZCOUNT key min max specifies the number of elements within the score range, and supports open and closed ranges.

ZRANGE key start end [WITHSCORES] gets a list of elements ranked in a certain range, sorted by scores from smallest to largest. Scores are optional. In the closed interval, end can be negative, which is consistent with the requirement of lrange parameters.

ZREVRANGE key start end [WITHSCORES] is sorted by score from highest to lowest.

ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] returns elements whose scores are in the closed interval [min,max] in order of score from smallest to largest. You can specify an open interval and precede the min with "(", which means (min, max). Inf and-inf are supported. Offset and count refer to offsetting offset elements backward based on the obtained list of elements and getting only the first count elements.

ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count] returns elements whose scores are in the closed interval [min,max] in order of number from highest to lowest. Note the parameter positions of max and min.

ZREM key member [member...] deletes one or more elements

ZREMRANGEBYRANK key start end deletes elements by range, with closed intervals. The index starts at 0.

ZREMRANGEBYSCORE key min max ranks by score, deletes elements with scores in [min,max], and supports open range.

ZRANK key member sorts from small to large by score, and gets the ranking of element member. The ranking with the lowest score is 0

ZREVRANK key member ranks element member in order of score from largest to smallest, and the ranking with the highest score is 0

ZINTERSTORE destination numkeys key [key...] [WEIGHTS weight [weight...]] [AGGREGATE SUM | MIN | MAX] calculates the intersection of numkeys ordered sets, stores them in the ordered set destination, and returns the number of elements of destination.

The WEIGHTS parameter sets the weight of each collection, and when each collection participates in the calculation, the score of the element is multiplied by the weight of the set.

AGGREGATE represents how the element score in the destination is calculated:

When AGGREGATE is SUM (the default), the score of the element in destination is the sum of that element's score in each collection that participates in the calculation.

When AGGREGATE is MAX, the score of the element in destination is the maximum score for that element in each collection participating in the calculation.

When AGGREGATE is MIN, the score of the element in destination is the minimum score for that element in each collection participating in the calculation.

ZUNIONSTORE destination numkeys key [key...] [WEIGHTS weight [weight...]] [AGGREGATE SUM | MIN | MAX] is similar to the above.

127.0.0.1 zadd zset1 6379 > 10 sh 40 bj # # add 2 elements (integer) 2127.0.0.1 zadd zset1 6379 > zadd zset1 20 sh 50 hz 80 cd # # update 1, add 2 (integer) 2127.0.0.1 zadd zset1 6379 > zscore zset1 sh # # to get the score of sh Updated to 20 "20" 127.0.0.1 zrange zset1 1-1 # # all elements starting from the second element 1) "bj" 2) "hz" 3) "cd" 127.0.1 zrange zset1 0-1 withscores # # get all elements 1) "sh" 2) "20" 3) "bj" 4) "40" 5) "hz" 6) "50" 7) "cd" 8) "80" 127.0.0.1 zadd zset1 inf zy # # add positive infinity (integer) 1127.0.0.1 zrangebyscore zset1 (elements with 50 inf withscores # # scores greater than 50) "cd" 2) "80" 3) "zy" 4) "inf" 127.0.1 zrangebyscore zset1 elements with scores greater than or equal to 50 Start with the second one. Take two 1) "cd" 2) "80" 3) "zy" 4) "inf" 127.0.0.1 hz 6379 > zincrby zset1 5 hz # # to add 5 points to the element hz "55" 127.0.1 zincrby zset1 6379 > zrangebyscore zset1 (50 inf # # successfully added 1) "hz" 2) "cd" 3) "zy" 127.0.0.1 zrange zset1 0-1 WITHSCORES # # query all elements 1) sh " "2)" 20 "3)" bj "4)" 40 "5)" hz "6)" 55 "7)" cd "8)" 80 "9)" zy "10)" inf "127.0.0.1inf 6379 > zcount zset1 0 inf # # get the number of elements (integer) 5127.0.0.1cd 6379 > zcount zset1 (55 inf # # greater than 55 elements (integer) 2127.0.0.1 integer > zrem zset1 zy # delete Except zy (integer) 1127.0.0.1 zrange zset1 0-1 # # the remaining four are 1) "sh" 2) "bj" 3) "hz" 4) "cd" 127.0.1 zrange zset1 6379 > zremrangebyrank zset1 12 # # by ranking Delete the 2nd to 3rd place (integer) 2127.0.0.1 zrange zset1 6379 > zrange zset1 0-1 # # only 2) "sh" 2) "cd" 127.0.0.1 sh 6379 > zadd zs1 1 a 2 b (integer) 2127.0.1 sh 6379 > zadd zs2 10 a 20 b (integer) 2 colors # zs1 and zs2 take the intersection, the weight of zs1 is 1, the weight of zs1 is 0. 5 So the result score of an is 1 "10" 0.5 "6127.0.1" AGGREGATE sum 6379 > zinterstore zs3 2 zs1 zs2 WEIGHTS 1 0.5 AGGREGATE sum (integer) 2127.0.1 "zrange zs3 0-1 withscores1)" a "2)" 6 "3)" b "4)" 12 "use.

A sorted scene. For example, sort the list of articles by the number of blog visits. Key is the data in the user id,set is the article id, and each article id is associated with a score (number of visits).

Comparison with list

Can get a certain range of elements.

The list type is realized through the linked list, the speed of obtaining data at both ends is fast, and when the number of elements is increased, the speed of accessing intermediate data is slow. So it is suitable for scenarios such as "new things" and "logs".

Ordered collections are implemented through hash tables and jump tables, so the data in the middle is also read very quickly. Time complexity O (log (N)).

Lists cannot simply adjust the position of an element, ordered collections can. (modify the score of the element)

The above is all the contents of the article "sample Analysis of basic types and usage of redis". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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