This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1. Basic command Redis

# Switch database
	SELECT index
# Amount of data currently available in the database
	DBSIZE
# Clear the current database content
	FLUSHDB
# Clear all database contents
	FLUSHALL
Copy the code

1.1 the key

# Delete key (one or more)
	DEL key [key ...]	
# Serialize the value of the specified key
	DUMP key	
# Query whether key exists
	EXISTS key	
# Set a key expiration time (s)
	EXPIRE key seconds	
(s) (-1, permanent; -2, invalid, no key)
	TTL key		
# Remove expiration time of key
	PERSIST key
# Find all keys that match a given pattern (wildcard: *: represents all; ? : represents a character.)
	KEYS pattern	
# returns a random key
	RANDOMKEY
# Rename a key
	RENAME key newkey
# Rename a key. The new key must be a nonexistent key
	RENAMENX key newkey
Move a key to another database
	MOVE key db
Copy the code

Application scenario of the EXPIRE key command

  • For a limited time
  • Mobile phone verification code
  • Limit the frequency of visitors to your site

1.2 Naming conventions for keys

A single key in Redis is saved to 512 megabytes.

In NOSQL, there is no association between data and data, which is solved by naming.

  1. The key should not be too long, try not to exceed 1024 bytes, this not only consumes memory, but also reduces query efficiency;
  2. The key should not be too short, too short, readability is reduced;
  3. In a project, it is best to use a uniform naming pattern for keys, such as: user: ID :name, user&ID&name;
  4. The name of the key is case sensitive and the command is case insensitive.

2. Redis data type

2.1 the String

2.1.1 introduction:

String is the most basic redis data type. A key corresponds to a value. A key can store up to 512MB.

The string type is binary safe, meaning that the Redis string can contain any data, such as JPG images or serialized objects.

Binary security is to ensure the information security of binary data during data transmission, that is, not to be tampered with, deciphered and so on. If attacked, it can be detected in time.

Binary security features:

  • The encoding and decoding are completed in the client and the execution efficiency is high.
  • Do not need frequent encoding decoding, will not appear garbled

2.1.2 string command

Assignment syntax
Set the value of the given key, overriding the old value if the key already exists, regardless of the type
	SET key value
If key does not exist, assign a value to key; The command is invalid because the key exists
	SETNX Key value // Important, distributed lock problem
# Assign multiple key-values
	MSET key value [key value...]
Append a value to the key, returning the length of the string
	APPEND key value
Copy the code
# Value syntax
Return the value of the key
	GET key
# Get a string of values stored on the key, start-end = value range (0-x)
	GETRANGE key start end
# Set the value of a key and get the value before setting it (widely used)
	GETSET key value
Get the length of the specified key value
	STRLEN key
# Returns the bit value stored at the offset of the key string value
	GETBIT key offset
Copy the code
# Delete syntax
Select * from key where key is deleted;
	DEL key
Copy the code
# increment, decrement, and return the number of results
If the key does not exist, then the key will be initialized to 0 and incr will be performed
	INCR key
If the key does not exist, the value of the key will be initialized to 0 and the incrby operation will be performed
	INCRBY key increment
# since minus one
	DECR key
# Decrement custom values
	DECRBY key increment
Copy the code

2.1.3 Application Scenarios

  • String is usually used to hold a single String or JSON String data;
  • Since strings are binary safe, it’s perfectly possible to store the contents of an image file as strings;
  • Counter, (regular key-value cache application, regular technique: number of reads, number of comments)

**INCR and other instructions themselves have the characteristics of atomic operation, ** so we can fully use INCR, INCRBY, DECR, DECRBY and other instructions to achieve the effect of atomic counting.

Many websites use this feature of Redis to achieve business statistics requirements.

2.2 the hash type

2.2.1 profile

  • A hash is a string mapping table of fields and values. Hashes are particularly useful for storing objects.

  • Redis can store 2^ 32-1 key-value pairs (more than 4 billion). It can be considered a map with keys and values. This type is ideal for storing information about VALUE objects such as uname, Ugender, and Uage. This type of data consumes very little disk space (compared to JSON).

2.2.2 hash commands

Assignment syntax
Key: object name field: property name value: property value
	HSET key field value
# Set multiple field-value pairs to the hash key simultaneously
	HMSET key field value [field value]...
Copy the code
# Value syntax
Select * from key
	HGET key field
Select * from key
	HMGET key field [field...]
Retrieve all fields and values of the key
	HGETALL key
Retrieve all fields in key
	HKEYS key
Get the number of fields in the key
	HLEN key
Copy the code
# Delete syntax
Redis deletes one or more fields from a key. When all fields are deleted, redis deletes the key
		HDEL key field [field...]
Copy the code
# Other syntax
Set field value only if key does not exist
	HSETNX key field value
# Add increment increment to the integer value of the specified key in the hash table
	HINCRBY key field increment
# Add increment increment to the floating point value of the specified field in the key of the hash table
	HINCRBYFLOAT key field increment
Check whether the specified field exists in the key of the hash table
	HEXISTS key field
Copy the code

2.2.3 Application Scenarios

  • Often used to store an object;

  • Why not store an object in string?

    • Hash is the data type closest to the structure of a relational database. It can convert a database record or an object in a program into a Hashmap and store it in Redis.

    • There are two ways to store objects in strings:

      • The first is to use the user ID as the lookup key and wrap the rest of the information into an object and store it serialized (JSON). Disadvantages: Increased serialization/deserialization overhead, and need to modify one of the information, the whole object needs to be taken out, and the modification operation needs to protect the concurrency, introducing complex problems such as CAS;
      Example: key: id, value:{json string}
      Copy the code
      • In the second case, key-Vale pairs are stored as many members as the user information object has, and the user ID+ the name of the corresponding attribute is used as the unique representation to obtain the value of the corresponding attribute. (example: set user:id 1; Set the user: the name xiaojian; Set user:gender “male”) saves serialization overhead and concurrency issues, but with user ids stored repeatedly, there is a huge memory waste if there is a lot of data like this.
    Ex. :
    key:user:id 1
        user:name xiaojian
        user:age 22
    Copy the code

2.3 the List type

2.3.1 profile

A simple list of strings, sorted by insertion order. You can add an element to the top (left) or bottom (right) of a list

List stores the elements in a stack structure, first in and last out

Similar to Java’s LinkedList

127.0.0.1:6379> lpush list2 1
(integer) 1
127.0.0.1:6379> lpush list2 2
(integer) 2
127.0.0.1:6379> lpush list2 3
(integer) 3
127.0.0.1:6379> lpush list2 3
(integer) 4
127.0.0.1:6379> lrange list2 0 -1
1) "3"
2) "3"
3) "2"
4) "1"
Copy the code

2.3.2 List command

Assignment syntax
Stores one or more elements from the left side of the list
	LPUSH key value[value...]
# Save a list from the left side of the list when it exists
	LPUSHX key value
Stores one or more elements from the right side of the list
	RPUSH key value[value...]
# Save a list from the right side of the list when it does not exist
	RPUSHX key value
Inserts an element before or after another element in the list
	LINSERT key BEFORE|AFTER pivot value
Such as: linsert List1 BEFORE "c"; list1 BEFORE "c";
Set the value of an element in the list according to the index
	LSET key index value
	
Copy the code
# Value syntax
# Get an element by its index
	LINDEX key index
Start and stop offsets are -1 for the last element, -2 for the penultimate element, and so on
	LRANGE key start stop
# Get the list length
	LLEN key
# Intercepts data in the specified range. The data in the list is changed to the intercepted data
	LTRIM key start stop
Copy the code
# Delete syntax
# remove an element from the leftmost part of the list and return it
	LPOP key
# Remove an element from the rightmost part of the list and return it
	RPOP key
# Remove value from key list
# if count is positive, remove the first count; For a negative number, count after removal; If 0, remove all values
	LREM key count value
Copy the code

2.3.3 Application Scenarios

  • On the data volume display, attention list, fan list, comment and so on… Pagination, hot news (Top5), etc.

    LRANGE can also be very convenient to achieve the function of paging; In the blog system, comments for each blog post can also be stored in a separate list.

  • Task queue

    A list is usually used to implement a message queue and to ensure ORDER without having to use ORDER BY as MySQL does

    Introduction to task queues (producer and consumer patterns) :
    # When processing command requests from web clients, some operations may take longer than we expected by queueing information about the task to be executed
    The user can defer operations that will take some time to complete, leaving the work to the task processor
    This is called a task queue The queue).
    
    	RPOPLPUSH source destination
    # add the last element in a list and add it to another list and return the last element in a list
    Copy the code

2.4 the Set type

Against 2.4.1 profile

A collection of duplicate elements is not allowed, unordered

Redis collection is implemented by hash table, so the complexity of adding, deleting and searching is O(1).

A set is implemented using a Hashtable,

The maximum number of members in the set is 2^32^ -1 (4294967295, each set can store more than 4 billion members)

Similar to the member Hashtable collection in Java

The Set command 2.4.2

Assignment syntax
# Add one or more elements
	SADD key member [member...]
Copy the code
# Value syntax
# Get all elements in the collection
	SMEMBERS key 
# Get the length of the collection
	SCARD key
# Determine whether the member element is a member of the set key.
	SISMEMBER key member
Returns one or more random numbers in the collection
	SRANDMEMBER key [count]
# difference set syntax:
	SDIFF Key1 [KEY2] : Returns the set of differences between a given key1 set and other sets
	SDIFFSTORE Destination key1 [key2] : returns the difference set of all given sets and stores it in destination (destination is the name of a newly created key)
# intersection syntax:
	SINTER Key1 [key2] : returns the intersection of all given sets (shared data)
	SINTERSTORE Destination key1 [key2] : returns the intersection of all sets given and stores it in destination (destination is the name of a new key)
# Union syntax:
	SUNION Key1 [key2] : Returns the union of all given sets
	SUNIONSTORE Destination key1 [KEY2] : Returns the union of all given collections and stores them at destination
	
Copy the code
# Delete syntax
Delete one or more elements
	SREM key member1 [member2]
# Remove and return a random element of the collection
	SPOP key [count]
Move the member element from the source collection to the Destination collection
	SMOVE source destination member 
Copy the code

2.4.3 Application Scenarios

It is often used to calculate the intersection, union and difference of data between two sets

  • Using the set operation, you can take the intersection of different interest circles, in order to achieve very convenient common concerns, common preferences, two degrees of friends and other functions. For all of the above collection operations, you can also use different commands to choose whether to return the results to the client or to store them in a new collection.
  • With uniqueness, you can count all the individual IP addresses that visit the site, and the list of active users on the day (or day) of access.

2.5 ZSet type

2.5.1 profile

Sorted set

Duplicate elements are not allowed, and the elements are ordered

Each element is inserted with a score of type double, sorted from smallest to largest

The members of an ordered set are unique, but scores can be repeated

(We call ordered sets in Redis zsets because in Redis, ordered sets are related to operations that start with Z.)

2.5.2 ZSet command

Assignment syntax
	ZADD key score member [score member...]
Copy the code
# Value syntax
# Get the number of members of an ordered collection
	ZACARD key 
Computes the number of members of a specified interval fraction in an ordered set
	ZCOUNT key min max
Returns the index of the specified member in an ordered collection
	ZRANK key member
Return the members of the specified interval (0, -1) in the ordered collection by indexing interval
	ZRANGE key start end [WITHSCORES]
# Returns the members of the interval specified by the ordered set as fractions
	ZRANGBYSCORE key min max [WITHSCORES] [LIMIT]
# Return the members of the specified interval of an ordered collection, indexed from highest to lowest
	ZREVRANGE key start stop [WITHSCORES]
# Returns the members of an ordered collection that specifies a fraction range, indexed from highest to lowest
	ZREVRANGEBySCORE key max min [WITHSCORES]
Copy the code
# Delete syntax
# Remove collection
	DEL key
# Remove one or more members from an ordered collection
	ZREM key member [member ...]
Copy the code

2.5.3 Application Scenarios

Often used in: leaderboards

Sales ranking, score ranking, etc

2.6 HyperLogLog

Introduction to the

Redis added HyperLogLog structure in version 2.8.9. Redis HyperLogLog is an algorithm for cardinality statistics. The advantage of HyperLogLog is that when the number or volume of input elements is very large, the space required for cardinality calculation is always fixed and smallCopy the code
In Redis, each HyperLogLog key costs only 12 KB of memory to calculate the cardinality of nearly 2^64 different elements. This is in contrast to a collection where more elements cost more memory when calculating cardinality. However, because HyperLogLog only calculates cardinality based on the input elements and does not store the input elements themselves, HyperLogLog cannot return the individual elements of the input as a collection can.Copy the code
What is cardinality? For example, the data set {1,3,5,7,5, 8}, then the cardinality set of this data set is {1,3,5,7,8}, and the cardinality (non-repeating elements) is 5. Cardinality estimation is to calculate cardinality quickly within the acceptable range of error.Copy the code

2.6.1 Common Commands

Add the specified element to HyperLogLog
	PFADD key element [element ...]
# Returns the cardinality estimate for a given HyperLogLog
	PFCOUNT key [key ...]
# Merge multiple HyperLogLog into one HyperLogLog
	PFMERGE destkey sourcekey [sourcekey ...]
Copy the code

2.6.2 Application Scenarios

The base is not large, the data volume is not large, it will be a little overqualified waste of space

There are limitations, that is, only the number of statistics base, and no way to know what the specific content is

Number of registered IP addresses Number of daily VISITS Number of real-time UV pages Number of online users Number of daily searches for different terms Number of actual articles readCopy the code