String

String is the most basic type of redis. You can understand it as exactly the same type as Memcached. A key corresponds to a value.
The string type is binary safe. This means that the redis string can contain any data. Such as jpg pictures or serialized objects.
The string type is the most basic data type in Redis, and the value of the string type can store up to 512MB

scenes to be used

Conventional key-value caching application, conventional counting: the number of Weibo, the number of fans

Related commands

SET key value Set key=value
GET key or the value corresponding to the key key
GETRANGE key start end Get the substring of the string stored in a key
GETSET key value Set the string value of the key and return the old value
GETBIT key offset returns the offset of the string value stored in the key value
MGET key1 [key2..] Get all the values ​​of a given key
SETBIT key offset value Set or clear the bit offset in the string value stored in the key
SETEX key seconds value Set value when the key expires
SETNX key value Set the value of the key, only if the key does not exist
SETRANGE key offset value covers the offset of a part of the string from the specified key
STRLEN key gets the length of the value stored in the key
MSET key value [key value...] Set multiple keys and multiple values
MSETNX key value [key value...] Set multiple keys and multiple values, only when there is no key
PSETEX key milliseconds value Set the milliseconds value and expiration time of the key
INCR key Increase the integer value of the key once
INCRBY key increment increments the integer value of the key by the given amount
INCRBYFLOAT key increment increments the floating point value of the key by a given amount
DECR key The integer value of the decrement key once
DECRBY key decrement Decrements the integer value of the key by a given number
APPEND key value Append value to a key

Commands for managing keys

DEL key if there is a delete key
DUMP key returns the serialized version of the value stored in the specified key
EXISTS key This command checks whether the key exists
EXPIRE key seconds Specifies the expiration time of the key
EXPIREAT key timestamp The specified key expiration time. Here, the time is in Unix timestamp format
PEXPIRE key milliseconds Set the key to expire in milliseconds
PEXPIREAT key milliseconds-timestamp Set the key to expire in milliseconds specified in the Unix timestamp
KEYS pattern finds all keys that match the specified pattern
MOVE key db Move key to another database
PERSIST key Remove expired key
PTTL key obtains the expiration key of the remaining time in milliseconds.
TTL key Gets the remaining time when the key expires.
RANDOMKEY returns a random key from Redis
RENAME key newkey change the name of the key
RENAMENX key newkey rename the key, if the new key does not exist
TYPE key returns the value of the data type stored in the key.

List

The Redis list is a simple list of strings, which can be compared to the std::list in C++, which is simply a linked list or a queue. You can add elements to the Redis list from the head or tail. The maximum length of the list is 2^32-1, which means that each list supports more than 4 billion elements.

The implementation of Redis list is a doubly linked list, which can support reverse lookup and traversal, which is more convenient to operate, but it brings some additional memory overhead. Many implementations in Redis, including sending buffer queues, also use this data. structure

Application scenario

There are many application scenarios for Redis list, and it is also one of the most important data structures of Redis. For example, Twitter's watch list, fan list, etc. can all be implemented with Redis's list structure. For example, some applications use Redis's list type to implement a simple Lightweight message queue, producer push, consumer pop/bpop

Related commands

BLPOP
BLPOP key1 [key2] timeout Take out and get the first element in the list, or block until it is available

BRPOP
BRPOP key1 [key2] timeout Take out and get the last element in the list, or block until it is available

BRPOPLPUSH
BRPOPLPUSH source destination timeout pops a value from the list, pushes it to another list and returns it; or blocks until it is available

LINDEX
LINDEX key index gets the corresponding element from a list and its index

LINSERT
LINSERT key BEFORE|AFTER pivot value Insert an element after or before other elements in the list

LLEN
LLEN key to get the length of the list

LPOP
LPOP key gets and takes out the first element in the list

LPUSH
LPUSH key value1 [value2] Preceded by a list of one or more values

LPUSHX
LPUSHX key value is preceded by a list of values, only if it exists in the list

LRANGE
LRANGE key start stop Get various elements from a list

LREM
LREM key count value Remove elements from the list

LSET
LSET key index value sets the value of an element at the index in the list

LTRIM
LTRIM key start stop Trim the list to the specified range

RPOP
RPOP key takes out and gets the last element in the list

RPOPLPUSH
RPOPLPUSH source destination delete the last element of the list, append it to another list and return it

RPUSH
RPUSH key value1 [value2] Add one or more values ​​to the list

RPUSHX
RPUSHX key value Add a value list, only if the list exists

Hash (dictionary, hash table)

Redis Hash corresponds to Value internally is actually a HashMap. Actually, there are two different implementations. In order to save memory, Redis will use a one-dimensional array for compact storage instead of a real HashMap structure. The encoding of the corresponding value redisObject is zipmap. When the number of members increases, it will be automatically converted to a real HashMap. At this time, the encoding is ht

Note that Redis provides an interface (hgetall) to get all the attribute data directly, but if there are many members of the internal Map, it involves the operation of traversing the entire internal Map. Due to the Redis single-threaded model, this traversal operation may be more complicated. Time-consuming, and other client requests do not respond at all, this requires special attention

Application scenario

Assuming that there are multiple users and corresponding user information, they can be used to store the user ID as the key and serialize the user information into, for example, json format as the value to save

Related commands

HDEL
HDEL key field[field...] delete one or several attribute fields of the object, the non-existent attributes will be ignored

HEXISTS
HEXISTS key field Check whether the object exists in this attribute field

HGET
HGET key field Get the value of the field in the object

HGETALL
HGETALL key Get all the attribute domains and values ​​of the object

HINCRBY
HINCRBY key field value increases the value of the specified field in the object by the given value. The atomic self-increment operation can only be the attribute value of integer.

HINCRBYFLOAT
HINCRBYFLOAT key field increment Increase the value of the specified field in the object by a given floating point number

HKEYS
HKEYS key Get all the attribute fields of the object

HVALS
HVALS key Get all the attribute values ​​of the object

HLEN
HLEN key Gets the total number of all attribute fields of the object

HMGET
HMGET key field[field...] Get the value of one or more specified fields of the object

HSET
HSET key field value Set the value of the specified field of the object

HMSET
HMSET key field value [field value ...] Set the value of one or more fields in the object at the same time

HSETNX
HSETNX key field value sets the value of the field only when the specified field does not exist in the object

HSTRLEN
HSTRLEN key field returns the string length of the value of the specified field of the object. If the object or field does not exist, it returns 0.

HSCAN
HSCAN key cursor [MATCH pattern] [COUNT count] Similar to SCAN command

Usage example

127.0.0.1:6379> hset person name jack
(integer) 1
127.0.0.1:6379> hset person age 20
(integer) 1
127.0.0.1:6379> hset person sex famale
(integer) 1
127.0.0.1:6379> hgetall person
1) "name"
2) "jack"
3) "age"
4) "20"
5) "sex"
6) "famale"
127.0.0.1:6379> hkeys person
1) "name"
2) "age"
3) "sex"
127.0.0.1:6379> hvals person
1) "jack"
2) "20"
3) "famale"

Set

It can be understood as a bunch of lists with non-repeating values, similar to the concept of sets in the field of mathematics, and Redis also provides operations such as intersection, union, and difference for sets.

The internal implementation of set is a HashMap whose value is always null. In fact, it is quickly sorted by calculating the hash. This is also the reason why set can provide to determine whether a member is in the set.

Application scenario

The external function provided by Redis set is similar to the function of a list. The special feature is that the set can automatically sort the weight. When you need to store a list of data and do not want duplicate data, set is a good choice , And set provides an important interface for judging whether a member is in a set collection, which is also not provided by list.

Or in a Weibo application, where each user follows a set of people, it is easy to achieve the function of asking two people to share friends.

Related commands

SADD
SADD key member [member ...] Add one or more elements to the set

SACRD
SCARD key Get the number of elements in the collection

SDIFF
SDIFF key [key ...] Get elements that do not exist in the queue

SDIFFSTORE
SDIFFSTORE destination key [key ...] Get elements that do not exist in the queue and store them in a key result set

SINTER
SINTER key [key ...] Get the intersection of two sets

SINTERSTORE
SINTERSTORE destination key [key ...] Obtain the intersection of two sets and store them in a set

SISMEMBER
SISMEMBER key member determines that a given value is a member of a set

SMEMBERS
SMEMBERS key Get all the keys in the collection

SMOVE
SMOVE source destination member moves a key in the collection to another collection

SPOP
SPOP key [count] Get and delete elements in a collection

SRANDMEMBER
SRANDMEMBER key [count] Get an element randomly from the set

SREM
SREM key member [member ...] Remove one or more elements from the set, non-existent elements will be ignored

SUNION
SUNION key [key ...] Add multiple set elements

SUNIONSTORE
SUNIONSTORE destination key [key ...] Combine set elements and store the result in the new set

SSCAN
SSCAN key cursor [MATCH pattern] [COUNT count] Iterate over the elements in the set

Usage example

redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SMEMBERS myset
1) "World"
2) "Hello"
redis> SADD myset "one"
(integer) 1
redis> SISMEMBER myset "one"
(integer) 1
redis> SISMEMBER myset "two"
(integer) 0

The realization of the list of friends

redis 127.0.0.1:6379> sadd friends:leto ghanima paul chani jessica
(integer) 4
redis 127.0.0.1:6379> sadd friends:duncan paul jessica alia
(integer) 3
redis 127.0.0.1:6379> sismember friends:leto jessica
(integer) 1 #No matter how many friends a user has, we can efficiently (O(1) time complexity) identify whether user X is a friend of user Y
redis 127.0.0.1:6379> sismember friends:leto vladimir
(integer) 0
redis 127.0.0.1:6379> sinter friends:leto friends:duncan #We can check whether two or more people have friends in common
1) "paul"
2) "jessica"
redis 127.0.0.1:6379> sinterstore friends:leto_duncan friends:leto friends:duncan # can store results in a new keyword
(integer) 2

Sorted Set (Ordered Set)

Redis ordered collection is similar to Redis collection, the difference is that a function is added, that is, the collection is ordered. Each member of an ordered set carries a score for sorting.

The time complexity of adding, deleting, and testing a Redis ordered set is O(1) (fixed time, regardless of the number of element sets contained in it). The maximum length of the list is 2^32-1 element (4294967295, a collection of more than 4 billion elements per element).

Redis sorted set uses HashMap and skip list (SkipList) internally to ensure the storage and order of data. HashMap puts the mapping of members to score, and the skip table stores all members, and the sorting basis is stored in HashMap. The score, the structure of the jump table can be used to obtain a relatively high search efficiency, and the implementation is relatively simple

scenes to be used

The usage scenario of Redis sorted set is similar to set. The difference is that set is not automatically ordered, while sorted set can sort the members by providing an additional priority (score) parameter by the user, and it is inserted in order, that is, automatic sorting. . When you need an ordered and non-repeating set list, you can choose the sorted set data structure. For example, the public timeline of twitter can be stored with the publication time as the score, so that it is automatically sorted by time when it is obtained.

For another example, the user's point ranking requirements can be achieved through an ordered collection. There is also the use of List to implement lightweight message queues described above. In fact, it is also possible to implement priority or weighted queues through Sorted Set.

Related commands

ZADD
ZADD key score1 member1 [score2 member2] Add one or more members to the ordered set, or update its score if it already exists

ZCARD
The number of ordered set members obtained by ZCARD key

ZCOUNT
ZCOUNT key min max calculates the score of an ordered set member and a given value range

ZINCRBY
ZINCRBY key increment member increases the score of a member in an ordered set

ZINTERSTORE
ZINTERSTORE destination numkeys key [key ...] Multiple cross-sorted collection, and store to generate a new key-ordered collection.

ZLEXCOUNT
ZLEXCOUNT key min max calculates the number of ordered set members between a given dictionary range

ZRANGE
ZRANGE key start stop [WITHSCORES] Returns an ordered set of member ranges (from low to high) by index

ZRANGEBYLEX
ZRANGEBYLEX key min max [LIMIT offset count] returns an ordered set of member ranges (by dictionary range)

ZRANGEBYSCORE
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] Returns in the ordered set key, all members whose score value is between min and max (including equal to min or max). The members of the ordered set are incremented by the score value (from small to large) Order

ZRANK
ZRANK key member determines the ordered set in the index of the member

ZREM
ZREM key member [member ...] Remove one or more members from the ordered set, non-existent members will be ignored

ZREMRANGEBYLEX
ZREMRANGEBYLEX key min max deletes all members in an ordered set between the given dictionary range

ZREMRANGEBYRANK
ZREMRANGEBYRANK key start stop deletes an ordered set of all members within a given index

ZREMRANGEBYSCORE
ZREMRANGEBYSCORE key min max deletes an ordered set of all members within a given score

ZREVRANGE
ZREVRANGE key start stop [WITHSCORES] Returns an ordered set of member ranges, sorted by scores by index, from high score to low score

ZREVRANGEBYSCORE
ZREVRANGEBYSCORE key max min [WITHSCORES] Returns an ordered set of member ranges, sorted by socre from high to low

ZREVRANK
ZREVRANK key member determines the index of an ordered set of members, sorted by score, from high score to low score

ZSCORE
ZSCORE key member Get the scores associated with a given member in an ordered set

ZUNIONSTORE
ZUNIONSTORE destination numkeys key [key ...] Add multiple sets to sort, and the resulting sorted set is stored in a new key

ZSCAN
ZSCAN key cursor [MATCH pattern] [COUNT count] Incremental iterative sorting of element sets and related scores

Usage example

redis 127.0.0.1:6379> zadd dbs 100 redis
(integer) 1
redis 127.0.0.1:6379> zadd dbs 98 memcached
(integer) 1
redis 127.0.0.1:6379> zadd dbs 99 mongodb
(integer) 1
redis 127.0.0.1:6379> zadd dbs 99 leveldb
(integer) 1
redis 127.0.0.1:6379> zcard dbs
(integer) 4
redis 127.0.0.1:6379> zcount dbs 10 99
(integer) 3
redis 127.0.0.1:6379> zrank dbs leveldb
(integer) 1
redis 127.0.0.1:6379> zrank dbs other
(nil)
redis 127.0.0.1:6379> zrangebyscore dbs 98 100
1) "memcached"
2) "leveldb"
3) "mongodb"
4) "redis"
Likes(0)

Comment list count 0 Comments

No Comments

WeChat Self-Service

WeChat Consult

TaoBao

support@elephdev.com

发表
评论
Go
Top