Redis -- 02 -- redis string structure and Application

1 string

Character array, redis string is a binary security string, which can store binary data such as pictures, as well as through
Binary data compressed by tools such as messagepack or protobuffer.

The internal actual storage can adopt int, embstr and raw storage according to the data characteristics of string (use object encoding key to view).

  • 1) If the string length is less than 20 and can be converted to numbers, use int to store the string.
  • 2) If 1 is not satisfied and the string length is less than 44, i.e. 0 < x < 20, but cannot be converted to a number plus a string in the range of 20 < = x < 44, embstr is used to store the string.
  • 3) If the string length is greater than 44, raw is used to store the string.
    For example:
192.168.1.9:6379> set hello world
OK
192.168.1.9:6379> get hello
"world"
192.168.1.9:6379>
192.168.1.9:6379>
192.168.1.9:6379> OBJECT encoding hello
"embstr"
192.168.1.9:6379> set hello 100
OK
192.168.1.9:6379> OBJECT encoding hello
"int"
192.168.1.9:6379> set hello 111111111111111111111111111111111111111111111111111111111111111111111111111111111
OK
192.168.1.9:6379> OBJECT encoding hello
"raw"

2 basic command

Redis detailed command view: http://redis.cn/commands.html .

2.1 SET,GET,INCR,INCRBY,DECR,DECRBY

# Set the value of key 
SET key value [EX seconds] [PX milliseconds] [NX|XX]
# Get the value of key 
GET key 

# The following four commands have features: if the specified key does not exist, it will be automatically created and its value will be set to 0 before incr operation.
# Perform an atomic plus one operation.
# Return value integer reply: the value corresponding to the key after the increment operation.
INCR key 
# Performs the operation of adding an integer to an atom.
# Return value integer reply: the value value after increase.
INCRBY key increment

# Perform atomic minus one.
# Return value number: the value after reduction.
DECR key 
# Performs the atomic subtraction of an integer.
# Return value number: the value after reduction.
DECRBY key decrement

result:

2.2 SETNX,DEL

# If the key does not exist, it is equivalent to the SET command. When the key exists, do nothing.
# Return value Integer reply, specific value: 1 if key is set. 0 if the key is not set.
SETNX key value

# Delete the specified batch of keys. If some keys in the deletion do not exist, they will be ignored directly. Return value integer reply: the number of deleted keys.
DEL key [key ...]

As you can see, because tyy exists, SETNX tyy 100 will not succeed, so the value returned by get tyy is still - 100.
Then delete. The deletion is very simple. You can use get tyy to see it. At this time, nil will be returned.

2.3 SETBIT,GETBIT,BITCOUNT
These commands are mainly used to operate binary bits. For example, binary bits can be used to record the clock out situation in a month. The clock out is set to 1 and the clock out is set to 0, and the number of days in a month can be counted.

# Set or clear the bit value of the value (string) of the key at offset. Offset represents binary bits, starting from 0. Value can only be 0 or 1
# Return value integer reply: returns the original bit value at offset.
SETBIT key offset value 
# Returns the bit value of the string corresponding to the key at offset.
GETBIT key offset 
# Count the number of bit s whose string is set to 1 
# Return value Integer reply: returns the number of bits set to 1.
BITCOUNT key
  • As shown in the figure below, the first two commands can determine that our offset starts from 0, because the first setbit returns the default 0, and then the second setbit returns the original value, that is, the value set for the first time.
  • Then, when setbit, when value is not 0 or 1, an out of bounds error will be reported.
  • Note that the second command, which is set to bit offset, is simply set to bit offset, and then to bit offset.

3 application

3.1 object storage

Strings can be used to store objects. At this time, the design of keys should be noted that they are generally named with "specific function: unique id describing this specific function". For example, the following: role plus its unique id. The following string is the specific object information of the key.

SET role:10001 '{["name"]:"tyy",["sex"]:"male",["age"]:24}' 
GET role:10001

String storage object information is generally in json format, but note:

  • json cannot mean special characters, such as \ 0, and will be truncated.
  • Because json needs to be stored after encoding and decoded after reading from redis, when using string as object storage, the object information should be fixed or hardly modified. Otherwise, you should use the hash dictionary mentioned later to store this object, because it is very fast and convenient for hash to modify individual fields.

Operation results:

3.2 accumulator

string incr and incrby can do some statistical information, which refers to accumulation. For example, the number of hits of wechat articles. Each time a user clicks an article to enter, we will accumulate it once, so that we can count the number of hits of articles.
Of course, you can also accumulate in memory each time. When the number of memory accumulation is 100, then use incrby to record, which can reduce the interaction between the code and the redis server, but you can't update the hits in real time. You can deal with it according to the actual scene.

Or Alipay's pace is the same.

# Add 1 to the total number of reading statistics 
incr reads 
# Add 100 in total 
incrby reads 100

3.3 distributed lock


For example, in the figure above, if four processes, that is, four clusters, access a resource in the same redis server at the same time, we need a lock to restrict it. If a process is accessing this resource, other processes cannot access it at this time. We can only try to access it after the process has accessed it. This lock is called distributed lock, which is the same as the common mutex lock.
Characteristics of distributed locks (understood according to mutual exclusion):

  1. Exclusivity: if someone visits, others cannot.
  2. Define the behavior of acquiring locks: only when locks are acquired can they be accessed.
  3. Define lock release behavior: release the lock, which means that this access is over, and others can apply for lock to access.

We can use setnx to implement this distributed lock.
For example, the following figure:

  • 1) First s1, get the lock. If you find the lock is useless, the lock succeeds. If s2 obtains the lock at this time, it will fail to obtain it, so 0 is returned. Now that the lock is obtained, you can access the shared data (assuming that get lock is the operation of accessing the shared data). After the access is completed, del lock releases the lock.
  • 2) After the first four commands (actually three, not setnx lock s2), a person successfully accesses the shared resource and releases the lock. At this time, s2 will lock successfully, then access the resources, and finally release the lock. The following figure is an example of two people accessing shared resources.

However, the following figure is just a simple simulation of distributed locks. Distributed locks in actual development will be more difficult and complex than this.

Precautions for distributed locks:

  • 1) setnx is equivalent to adding nx after the set command. For example:
SETNX lock s1
# Equivalent to
SET lock s1 nx
  • 2) If you have locked a lock and then lock this lock, it will also fail to lock, but it will not be stuck like a mutually exclusive lock.
    For example, next, s1 is locked, and then setnx lock s1 is locked. It is found that 0 is returned, but the client cli will not get stuck.

3) Why can't we use set to implement distributed locking? Because set can't be exclusive. For example, in the above example: when I access data after s1 is locked, and s2 is locked, it can also be successful. The correct thing is to let s2 wait, so set can't be exclusive.

3.4 bit operation

For example, use bit operation to process monthly check-in function.

# Monthly check-in function.
# Sign in function: sign in. 10001: user id. 202107: sign in in in July 2021. 1: The first day of July. 1 at the end: the representative signed in. 
setbit sign:10001:202107 1 1 

# Calculate the check-in in July 2021.
bitcount sign:10001:202107 

# Get the check-in status on the second day of July 2021.
# 1 signed in; 0 is not signed in.
getbit sign:10001:202107 2

Execute in redis:

Keywords: Database Redis Cache

Added by ten31studios on Tue, 22 Feb 2022 15:35:15 +0200