I. Introduction to Redis

Redis (Remote Dictionary Server) is a NoSql database.

What is a NoSql database?

Now with the current business of massive users and high concurrency business, make relational database encounter many bottlenecks. For example, performance bottleneck: A large amount of data is read and written, resulting in low DISK I/O performance. The scalability performance of relational databases is poor. In the case of more complex data relationships, the scalability of relational databases is poor and can no longer meet the requirements of large-scale clustering.

To solve these problems, first, reduce the number of disk accesses, consider adding memory to memory. Second: remove complex data relationships, as simple as possible, you can consider not storing relationships, only storing data

NoSql (NotOnlySql) is an extension of relational databases. It is characterized by capacity expansion, scalability, high performance, flexible data model and high availability under large data volume. Redis is a database of NoSql.

Redis is a high-performance key-value database that can be used as a database, cache, message middleware, and more

What is a key-value pair?

For mysql relational databases, the structure is: library-table-primary-key-information key-value pair is: k-V Key is always string, and Value can be the 5 data structures introduced in Chapter 2.

It is worth noting that Redis only stores hot data, not all data, and the basic data information is still stored in mysql. So Redis works with mysql.

Redis features: There is no necessary correlation between data

  • Internal use of single thread mechanism for work
  • High performance – Internal
  • Multiple data type support
  • Persistent support for data disaster recovery

Application scenarios :(we will elaborate on the corresponding scenarios for each data type later)

  • Accelerating query of hotspot data (main scenario). Hot commodities, hot news and other highly accessible information
  • Task queue, such as SEC kill, snap up
  • Real-time information query, such as leaderboards, online numbers, etc
  • Timeliness information control, such as captcha
  • The message queue
  • A distributed lock

Two, redis five data types

1, the String

Simplest type of data store. Each storage space holds only one data. If the string is a number, it is treated as a number. Redis all operations are atomic, using a single thread to process all business, commands are executed one by one, so there is no need to consider the impact of high concurrency on data

Maximum storage capacity: 512MB

Common operations

set key value / / assignment
get key // Get the value of the specified key
del key // Delete the specified key
incr key // Add one to the specified key
decr key // Subtract one from the specified key
incrby key increment // Add increment to the specified key
decrby key decrement // Decreases decrement for the specified key
Copy the code

Applicable scenario

1) The validity period of the vote

The life cycle of data can be specified to control when data fails. The corresponding business behavior of data failure control is used for time-limited control operations.

setnx key seconds value // Set the validity period of the key value to seconds
Copy the code

2) Data storage of BIG V user information: number of fans, blog posts, etc

To add a follower, use incr to add directly

Redis is used for a variety of data structure and unstructured hot data stream access.

Here is a description of the hot data key naming convention in the database: Use: split data hierarchy

3) Distributed locks

Distributed locking practices

2, the Hash

Groups stored data. Typical applications store object information. A single storage space can hold multiple key-value pair data. At the bottom is the implementation of the hash table.

Value stores only strings, and each hash can store 2^32-1 key-value pairs

Common operations

hset key field value // Set a field and value for the specified key
hmset key field1 value1 field2 value2 // Set multiple field and value values for the specified key
hget key field // Get the specified key and field values
hmget key field field2 // Get multiple key and field values
hgetall key // Get the values of all fields under the key. If there are too many internal fields, traversing the overall data efficiency will be time-consuming.
hdel key field1 field2 // Delete the specified field under the specified key.
hdel key // Delete all fields under the specified key
hexists key field // Check whether the field for the specified key exists
hlen key // Query the number of fields under the specified key
hkeys key // Get all fields under the specified key
hvals key // Get all values under the specified key
Copy the code

Applicable scenario

1) Shopping cart of e-commerce website

Shopping cart information, you can easily add, delete, change and check, management quantity, etc

2) Business information management

It is used for data storage design, such as snapping up, issuing consumer vouchers (until the end of delivery)

3, the List

When multiple data is stored, the sequence of data entering the storage space must be distinguished. Data mainly to reflect the order, the bottom of the bidirectional linked list implementation.

The list holds a maximum of 2^32-1 strings. List has the concept of an index.

Common operations

lpush key value1 value2 // Add value from the header to the specified key. If the key does not exist, it will be created automatically
rpush key value1 value2 // Add value from the end of the specified key. If the key does not exist, it will be created automatically
lrange key 0 - 1 // Get the value of the specified key from the start position to the end position, starting from 0 and ending with -1
lpop key // Pops the value of the specified key header, returns nil if key is not present, and returns the header element if it is
rpop key // Pops the value at the end of the specified key, returns nil if the key does not exist, and returns a tail element if it does
llen key // Gets the length of the specified key list, or 0 if no key exists
lpushx key value // Add value from the header of the specified key. Add value only if the key exists. Return 0 if the key does not exist
rpushx key value // Add value from the end of the specified key, as above
lrem key index value If index is greater than 0, all values equal to value are deleted. If index is less than 0, all values equal to value are deleted
lset key index value // Change the value of the specified position to the specified value. If the Angle index does not exist, ERR index out of range
linsert key before value newValue // Add a new value to the keylist before specifying a value
linsert key after value newValue // Add a new value before the specified value in the specified keylist, starting at the end
rpoplpush key key2 // Pop the tail element of the specified key into the head of key2. If the two keys are the same, the tail element is pressed in the same list
Copy the code

Applicable scenario

1) “like” in circle of friends, displaying friends in the order of “like”

Applied to data control with sequence of operations.

2) Paging operation

Usually the first page information comes from the list, and the rest of the page information is loaded from the database.

4, the Set

Store a large amount of data to provide better query efficiency in terms of query. The hash storage structure is the same as that of hash, except that only fileds values are stored, not values. Set does not allow data duplication and cannot enable the value function

Common operations

sadd key value1 value2 // Add data to the specified key
smembers key // Gets the element in the specified key
srem key members value1 value2 // Delete the specified value from the specified key
sismember key value // Check whether the specified value in the specified key exists. 1 is returned if the specified value exists, 0 is returned if the specified key does not exist, or the key itself is returned
sdiff key key2 // Get the elements of key that are different from key2.
sinter key key2 // Get the same element as in key2 (intersection)
sunion key key2 // Merge the key and key2 elements, not including the same elements (union)
scard key // Get the number of elements in the specified key
srandmember key // Randomly retrieves an element of the specified key
sdiffstore key key1 key2 // Store the difference between key1 and key2 in the key
sinterstore key key1 key2 // Store the intersection of key1 and key2 in the key
sunionstore key key1 key2 // Store the union of key1 and key2 in the key
spop key // Get a key to remove the data
Copy the code

Applicable scenario

1) Association search applied to similar messages

User A starts from user A and obtains the shopping list/game recharge list of common friend B (level 2)

2) Random recommendation information retrieval, such as recommended hot music, news, etc

3) Merge different types of non-repeated data, such as permission configuration

4) It is applied to fast deduplication of the same type of data, such as traffic statistics

5) Set service control based on blacklist and whitelist (using the de-duplication of SET)

5, Sorted_set

Requirement: Data sorting is conducive to the presentation of data, and it is necessary to provide a kind of sorting according to its own characteristics. Add score to set. Score does not store data, only for sorting.

Common operations

zadd key score name score2 name // Store score name in the specified key, if there is the same name overwrites the previous element, return the value of the newly added element, not the existing element
zscore key name // Get score for name in the specified key
zcard key // Get the number of members in the specified key
zrem key name name2 // Delete the value of name and name2 in the specified key
zrange key start end withscores // Returns the element from the start to the end of the specified key, without withscores, only name is returned, plus score is returned, from small to large
zrevrange key start end withscores// Returns the elements from the start to the end of the specified key in descending order, including both ends
zremrangebyrank key start end // Remove elements from the specified ranking range, from small to large, starting from 0
zremrangebyscore key min max // Remove elements from the specified range of fractions, including min and Max
zrangebyscore key min max withscores // Returns the size of the element in the specified range of fractions in the specified key
zrangebyscore key min max withscores limit start end Start and end are indexes
zincrby key score name // Add score to the element whose name is specified in the specified key and return the added score
zcount key min max // Returns the number of elements in the specified range of fractions in the specified key, including the start and end elements
zrank key name // Returns the rank (from smallest to largest) of the name element in the specified key, starting at 0
zrevrank key name // Returns the rank of the named element in the specified key, starting at 0
Copy the code

Applicable scenario

1) Establish a ranking basis for all participating resources. TOP10(songs, movies)

2) Scheduled task execution sequence management or expiration management. Membership system (monthly, quarterly, annual)

(time Indicates the current system time.)

conclusion

Reference:

Key-value pair database learning

Redis FAQ