The following is an excerpt from redis official website, which describes the data types supported by redis:
It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams.
The following describes only the first five commonly used.
A string (String)
1, the string type
In fact, it can be a string (including XML, JSON), numbers (integer, float), binary (images, audio, video), etc., but the maximum does not exceed 512MB.
2. Set command
set name zhangsan ex 10 // 10 milliseconds seconds expired expiration px 10000
setnx name zhangsan // if the key name does not exist is provided, arranged to return a success; if key name exists returns 0
set age 29 // key before the key age is covered by existing, successful return 1
Scene: Only one can be set by setnx success, do distributed lock; also available through setnx placeholder, to prevent the scene of successive calls
An order for values: get age // exists return value, nil return key does not exist
Batch Setting: mset name zhangsan age 15
Batch get mget name age // return zhangsan 15
Without mget command, will have n times get, thus affecting the performance of network resources occupied
Use mget = 1 times the internal network requests redis n queries, the query returns all disposable Results
3, count
No age incr age // increment key from 0 return 1; if the error is returned age die integer, then an integer of from 1 plus
decr age // Save integer from age 1, non-integer returns an error, no key age from 0 decremented -1
incrby age 2 // plus an integer of from 2, non-integer returns an error, no age from 0 to return from plus 22
decrby age 2 // Ibid.
incrbyfloat age 1.1 // integer age + 1.1
4, append additional instruction
set name zhang; after append name san // append return zhangsan
5, a string
set name "hello"; strlen name // return 6, 3 bytes each Chinese
6, the string interception
set name zhangsna; getrange name 2 4 // return ang
7, internal code
int: 8-byte integer
set age 100; object encoding age //返回int
embstr: 39 byte strings or less
set name zhangsan; object encoding name //返回embstr
Greater than 39 bytes string: raw
set name iafhsdfsdhfhusdfufdhhdghdbvjdvhdushfuisdhfudsihfusdhfuisgsvbnsdhfsduhfsduhfdsfhudhgfghdf
object encoding name //返回raw
8, switch databases
select 2 // 16 databases 0-15
9, application scenarios
Key design: Business name: Object Name: id: [Properties]
Database for the order, the user table user, a corresponding key may order: user: 1, order: user: name
note:
redis currently in protected mode, the client does not allow non-local links, you can set a password to redis, and then link the client when the sentence can write a password
127.0.0.1:6379>config set requirepas 123456 provisional entry into force
Or modify redis.conf requirepass 123456
When start: ./redis-server redis.conf specified conf
./redis-cli -p 6379 -a 12345678 // need to add a password to access
Second, the hash (hash)
A string field type and value of the mapping table when the hash. hash suitable for storing objects.
1, the command
hset key field value
Setter: hset user: 1 name zhangsan // successful return 1, else return 0
Value: hget user: 1 name // return zhangsan
Value-: hdel user: 1 nage // returns the number of deleted
Count the number of keys corresponding to fields:
hset user:1 name zhangsan; hset user:1 age 15;
hlen user: 1 // returns 2, user: 1 has two attributes
Batch set value: hmset user: 2 name zhangsan age 15 // return OK
Batch Value: hmget user: 2 name age // returns two rows zhangsan 15
Field determines whether there hexists user: 2 zhangsan // return a presence, absence returns 0
Get all field: hkeys user: 2 // Returns the name age two field
Obtain user: 2 All value: hvals user: 2 // return zhangsan 15
Obtain user: 2 all field and value: hgetall user: 2 // Returns the name zhangsan age 15
Increased 1:
hincrby user:2 age 1//15 + 1
hincrbyfloat user: 2 age 2 // float plus 2
2, the internal coding
ziplist <compression list> and hashtable <hash table>
When small and no large number of field value, the internal coding of ziplist
Example:
hmset user:3 name lisi age 20;object encoding user:3//返回ziplist
When the value is greater than 64 bytes, encoded by the internal programming hashtable ziplist
Example:
hset user: 4 name "Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang Wu Wang five ";
object encoding user:4//返回hashtable
hash types are sparse, each key can have different field, if relations do complex queries with development difficulties redis simulation, high maintenance costs.
3, three kinds of user information storing programs to realize
1) primeval
set user:1 nage haha;
set user:1 age 60;
Advantages: simple and intuitive, each key corresponds to a value
Cons: too many key number, occupation and more memory, user information is too scattered, not for production environments
2) The stored object serialization redis
set user:1 serialize(user)
Advantages: simple programming, high memory usage
Cons: serialization and de-serialization has some overhead, the user needs to update the property to take out all the deserialized, and then update the serialized into redis
3) use the hash type
hmset user:1 name hahs age 60
Advantages: simple and intuitive, can reduce the memory consumption
Disadvantages: To control ziplist and hashtable two encoding conversion, and consumes more memory hashtable
Summary: For the case of updating few, may be used serialization, for value not greater than 64 bytes may be used hash type
Third, the list (list)
1, for storing a plurality of ordered strings, a list of up to 32 power storage elements 2 Save 1
Because the order, you can get a list of elements within a range of elements or so by index, list elements can be repeated
2, a list of related commands
Add command: rpush lpush linsert
rpush name abcd // abcd inserted from right to left, it is a first insert
lrange name 0 -1 // from left to right to get a list of all the elements abcd
lpush fav abcd // insert from left to right abcd
lrange fav 0 -1 // from left to right to get a list of all the elements dcba
linsert fav before br // r inserted before B, then after, for use lrange fav 0 -1 returns dcrba
Find command: lrange index llen
lrange key start end // subscript index Features: from left to right from 0 to n-1, right to left if the rightmost first subscript -1, -2 .. The second .
lindex fav -1 // returns the rightmost end of a, -2 return b
llen fav // returns the current length of the list 5
Delete command: lpop rpop lrem ltrim
lpop fav // The first element of the leftmost deleted d
rpop fav // the rightmost element of a deleted
lrem key count value // delete the specified elements, count value of 0 means to delete all the value, count less than 0 indicates deleted from right to left to count the value of value
Example:
lpush test bbbbbjxz // key test put zxjbbbbb
lrange 0 -1 // test results for the zxjbbbbb
lrem test 4 b // b start deleting elements from the left, remove the four
// lrem test 8 b // delete 8 b, but only five are all deleted
lrange test results after 0-1 // delete as bjxz
lrem test 0 b // b retrieve all deleted all jxz
lpush user bbbbbjxz // user keys from left to right into the zxjbbbbb
Leaving only an entirely deleted ltrim user 1 3 // from the second to the fourth element xjb
lrange user 0 -1 // query results xjb, all other deleted
Modify the command: lset
lpush user1 zyx // key user1 plunged from left to right xyz
lset user1 2 java // z the third element is replaced java
lrange user1 0 -1 // query result xy java
Blocking command: blpop brpop
3, internal code list
1) When the number of elements and not less large element, coded as ziplist, reduce memory usage
rpush list a b c
object encoding list // return ziplist
2) When more than 512 elements, elements, or more than 64 bytes, coded into the internal list linkedlist
rpush list a1 a2.............a513或rpush list nnnnnnnnnnnnn.....nnn
object encoding list //linkedlist
In Version 3.2 billion euros, redis provides quicklist internal coding, which combines the advantages of both ziplist and linkedlist, before ziplist is a bug using qulicklist internal coding more efficient, so now you do not see these two after 3.2 encoding, only to see qulicklist.
Fourth, unordered collection set
Save multi-element, is not the same as the list does not permit duplicates, and are unordered set, a set can be stored up to 2 to give a minus power of 32 elements, in addition to supporting CRUD, supports set intersection, and union, difference;
1, elements of the collection set related commands
Operating elements: exists sadd smembers srem scard spop
exists user // to check whether there is a user key
sadd user abc // elements 3 inserted to the user, returns 3
sadd user ab // insert a straw to get too upset if more elements, repeat invalid, returns 0
srem user a // returns 1, delete a element
scard user // returns 2, the number of elements calculated
sismember user a // element in the set is determined whether the presence, presence of a return, there is no return 0
Random returns srandmember user a // two elements, the number of elements 2
spop user 2 // returns two random elements ab, and ab removed from the collection
smembers user // this time has been no ab, only c
Set intersection: sinter
add user:1 lili 22 girl
add user:2 zhangsan 22 boy
sinter user: 1 user: 2 // find the intersection of the two sets, then it returns 22
sadd user: 3 lucy 22 girl // add a third element
sinter user: 1 user: 2 user: 3 // find the intersection of the three sets, then it returns 22
Set union (de-emphasis): sunion
sunion user: 1 user: 2 user: 3 // merge the three sets, deduplication, returns lili zhangsan lucy girl boy
Set difference set: sdiff
sdiff user:1 user:2 //lili girl
Save the result set to the queue: sinterstore sunionstore sdiffstore
sinterstore user_jj user: 1 user: 2 // Save the results to the intersection user_jj
sunionstore user_bj user: 1 user: 2 // save the results to the union user_bj
sdiffstore user_cj user: 1 user: 2 // save the results to set the difference user_cj
smembers user_cj //返回lili girl
2, the internal coding
sadd user 1 2 3 4 // When the number of elements less (less than 512) and are integers, redis used to reduce the use of memory intset
If the number 12 513 @ .... sadd user when the element is not more than 512, or an integer (e.g., ab), encoded hashtable
object encoding user //hashtables
3, unordered set of application scenarios set
Label, social, inquiries have common interests of people, intelligent recommendation
Use:
Add tags to the user:
sadd user:1:fav basketball football
add user:2 pq
Or add users to the label:
sadd basketball:users user:1 user:2
sadd football:users user:1 user:2 user:3
...
Calculate the common interests of the people:
sinter user:1:fav user:2:fav
Fifth, ordered set
Commonly used in the list, such as video sites require users to upload video to do list, or the number of points Chan
And a collection of linked, can not have duplicate members
Ordered set with the set of differences and set the queue list:
1, the relevant command ordered set
Add Command
zadd key score member [score member....]
zadd user: zan 200 zhangsan // zhangsan Like a number of points, the number of successful operation returns 1
zadd user: zan 200 zhangsan 120 lisi 100 wangwu // returns 3
zadd test: 1 nx 100 zhangsan // Key test: 1 does not exist, mainly for adding
zadd test: 1 xx incr 200 zhangsan // Key test: 1 must be present, primarily for modifying, in this case 300
zadd test: 1 xx ch incr -299 zhangsan // returns the operation result 1,300-299 = 1
View command
zrange test: 1 0 -1 withiscores // view point Like (score) and Member Name
zcard test: 1 // count the number of members, a return
View the number of praise
zadd test: 2 nx 100 zahngsan // Add a collection
zscore test: 2 zhangsan // View lisi number of points (score) Chan returns 100
Ranking:
zadd user: 3 200 zhangsan 120 lisi 100 wangwu // Insert data first
zrange user: 3 0 -1 withscores // see the scores with members
zrank user: 3 zhangsan // return ranking: third place returns 2 from 0 to 2 of 3
zrevrank user: 3 zhangsan // return 0 anti-ordering, the higher the number of points like this, the more front rank
Delete command:
Remove members:
zrem user: 3 zhangsan lisi // returns successfully removed two members left wangwu
Increase the score:
zincrby user: 3 10 wangwu // king five members plus 10 scores
zadd user: 3 xx incr 10 wangwu // and said command as
Returns the specified range of scores and ranking member
zadd user: 4 200zhangsan 120 lisi 100 wangwu // Insert data first
zrange user: 4 0 -1 withscores // return result wangwu 100 lisi 120 zhangsan 200 (where the space is actually a line feed)
zrevrange user: 4 0 -1 withscores // reverse order, the result is zhangsan 200 lisi 120 wangwu 100
Returns the member specified fraction range
zrangebyscore user: 4 110 300 withscores // return result from low to high lisi 120 zhangsan 200
zrevrangebyscore user: 4 300 110 withscores // return the result to low zhangsan 200 lisi 120
zrangebyscore user: 4 (110 + inf withscores // 110 to infinity, the result is lisi 120 zhangsan 200
zrevrangebyscore user: 4 (110 -inf withscores // infinitely small to 110, the result is wangwu 100
Returns the number of members specified score range:
zcount user: 4 110 300 // returns 2, the two data and zhangsan lisi
Delete the specified elements in ascending order of rank:
zremrangebyrank user: 4 0 1 // points in ascending order, delete the first 0 and the first one, leaving only zhangsan
Remove members of a specified score range:
zadd user: 5 200 zhangsan 120 lisi 100 wangwu // to insert test data
zremrangebyscore user: 5 210 300 // 210 and delete members fraction range 300
zremrangebyscore User:. 5 (INF + 100 // delete fraction is greater than 100 (not including 100), left wangwu
Ordered set intersection:
格式:zinterstore destination numkeys key ... [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]
destination: the intersection of generating new elements to store key names
numkeys: do the number of key intersections calculated
key: key elements
weights: each value corresponding to the key selected by weight, default 1
Initialization data:
zadd user: 7 1 james 2 mike 4 jack 5 kate // initialize user: 7 Data
zadd user: 8 3 james 4 mike 4 lucy 2 lee 6 jim // initialize user: 8 Data
Intersection examples:
zinterstore user_jj 2 user: 7 user: 8 aggregate sum // 2 representative of the number of combined keys,
// aggregate sum may increase nor put, because the default is the sum
@ Results user_jj: 4james (1 + 3), 6mike (2 + 4)
zinterstore user_jjmax 2 user:7 user:8 aggregate max 或min
// on the intersection of the maximum score, return results 3james 4mike, min take minimum
weights:
zinterstore user_jjweight 2 user:7 user:8 weights 8 4 aggregate max
// 1, taking the intersection of two members of the same, user: 7-> 1 james 2 mike; user: 8-> 3 james 4 mike
// 2, the user: 7-> james 1 * 8 = 8, user: 7-> mike 2 * 8 = 16, the final user: 7 Results 8 james 16 mike;
// 3, the user: 8-> james 3 * 4 = 12, user: 8-> mike 4 * 4 = 16, the final user: 8 Results 12 james 16 mike
// 4, the final result of multiplying the maximum value of 12 james 16mike
// 5, zrange user_jjweight 0 -1 withscores query result 12 james 16mike
Summary: The user: 7 member value by 8, the user: 8 member value by 4, take the intersection, take maximum
Ordered set union (merge to weight):
格式:zunionstore destination numkeys key ... [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]
destination: the intersection of generating new elements to store key names
numkeys: do the number of key intersections calculated
key: key elements
weights: each value corresponding to the key selected by weight, default 1
zunionstore user_jjweight2 2 user:7 user:8 weights 8 4 aggregate max
// zinterstore as above, but taken and set as instructions
2. ordered set of internal code
1) ziplist
zadd user:9 20 james 30 mike 40 lee
object encoding user:9 //返回ziplist
//当元素个数少(小于128个),元素值小于64字节时,使用ziplist编码,可有效减少内存的使用
2)skiplist
zadd user:10 20 james......
//大于128个元素或元素值大于64字节时为skiplist编码
3.使用场景
排行榜系统,如视频网站需要对用户上传的视频做排行榜
点赞数:zadd user:1:20180106 3 mike //mike获得3个赞
再获一赞:zincrby user:1:20180106 1 mike //在3的基础上加1
用户作弊,将用户从排行榜删掉:zrem user:1:20180106 mike
展示赞数最多的5个用户:zrevrangebyrank user:1:20180106 0 4
查看用户赞数与排名:
zscore user:1:20180106 mike zrank user:1:20180106 mike