Basic knowledge of Redis

Redis installation

Download address:
 Installation steps:
# gcc installation
yum install gcc

# Download redis-5.0.3 tar. Put Gz in the / usr/local folder and unzip it
tar xzf redis-5.0.3.tar.gz
cd redis-5.0.3

# Enter the extracted redis-5.0.3 directory for compilation and installation

# Modify configuration
daemonize yes  #Background start
protected-mode no  #If the protection mode is turned off and turned on, only the local machine can access redis
# bind needs to be commented out
#bind (bind is bound to the ip of its own machine's network card. If there are multiple network cards that can be equipped with multiple IPS, it represents which network card ip of the machine allows the client to access. Generally, bind can not be configured in the intranet. Just comment it out)

# Start service
src/redis-server redis.conf

# Verify successful startup 
ps -ef | grep redis 

# Enter redis client 

# Exit client

# Exit redis service: 
(1)pkill redis-server 
(2)kill Process number                       
(3)src/redis-cli shutdown 

Redis's single thread and high performance

Is redis single threaded?
The single thread of redis mainly refers to the reading and writing of redis's network IO and key value pairs. The reading and writing of key value pairs is completed by a single thread, which is also the main process of redis providing external key value storage services. However, other functions of redis, such as persistence, asynchronous deletion and cluster data synchronization, are performed by additional threads.

Why is Redis single thread so fast?

Because all data of redis are stored in memory, all operations are memory level operations, and single thread avoids the loss of multi-threaded switching performance. Because redis is a single thread, you should use redis commands carefully. For those time-consuming instructions (keys *), you must use them carefully. If you are not careful, redis may get stuck.

How does Redis single thread handle so many concurrent client connections?

Redis's IO multiplexing: redis uses epoll to realize multiplexing, puts the connection information and time in the queue, and then puts them in the file event dispatcher, which distributes the files to the event processor.

Redis five data structures

String common operations

**//Common string operations
SET key value //Save string key value pair

MSET key value[key value] //Batch storage of string key value pairs

GET key     //Gets a string value

MGET key[key]  //Get string key values in batch

EXPIRE key seconds  //Set the expiration time of a key (seconds)

Atomic addition and subtraction
INCR key  //Add the value stored in the key + 1

DECR key   //Set the value stored in the key to - 1

INCRBY  key increment    //Add the value stored in key + increment

DECRBY key increment   //Set the value stored in the key to - increment

String application scenario


INCR article:readcount:{article id}

GET article:readcount:{article id}

HASH structure

HSET key field  value  //Store the value of a hash table key

HMSET key field value [field value ...]    //Store multiple values in a hash table

HGET key field    //Get the value of the field corresponding to the hash table key

HMGET key field [field...]   //Get the values of multiple field s corresponding to the hash table key

HDEL key field [field..]    //Delete the field corresponding to the key in the hash table

HLEN key  //Returns the number of field s in the hash table

HGETALL key //Returns all key values in the hash table 

HINCRBY key field  increment   //Add increment to the field value of the corresponding key in the hash table

HASH application scenario

E-commerce shopping cart

  • Take user id as key
  • The commodity id is field
  • The quantity of goods is value

Shopping cart operation

  • Add product hset cart:1001 10088 1
  • Increased quantity hincrby cart:1001 10088 1
  • Total number of goods hlen cart:1001
  • Delete commodity hdel cart:1001 10088
  • Get all goods in shopping cart hgetall cart:1001

Advantages and disadvantages of hash structure


  • Similar data is classified and stored to facilitate data management
  • Compared with String type operation, it consumes less memory and cpu
  • Save more space than String storage


  • The expiration function cannot be used on a field, but only on a key
  • Redis cluster architecture is not suitable for large-scale use

List schema

LPUSH key value [value ...]    //Insert one or more value values to the far left of the key

RPUSH key value [value ...]    //Insert one or more value values to the far right of the key

LPOP key   //Removes and returns the header element of the key list

RPOP key   //Removes and returns the last element of the key list

LRANGE key start stop  //  Returns the element of the specified interval in the key list

BLPOP key [key...] timeout  //Pop up an element from the list header. If there is no element in the list, wait for timeout seconds. If timeout=0, it will be blocked all the time

BRPOP key [key...] timeout  //Pop up an element from the end of the list. If there is no element in the list, wait for timeout seconds. If timeout=0, it will be blocked all the time

List application scenario

Common data structures

  • Stack = LPUSH +LPOP
  • Queue = LPUSH +RPOP
  • Blocking MQ = LPUSH + BRPOP

    WeChat news and WeChat official account message
    cn pays attention to gcx, yhj and other big V
  • gcx sends microblog with message id 10018
LPUSH msg:{cn-id} 10018
  • yhj sends microblog with message id 10086
LPUSH msg:{cn-id} 10086
  • View the latest microblog information
LRANGE msg:{cn-id} 0 4

SET structure

SADD key member [member...]  //Store elements into the set key, and ignore them if they exist

SREM key member [member...]  //Delete element member from set key

SMEMBERS key   //Get all elements in the set key

SCARD key //Gets the number of elements of the set key

SISMEMBER key member  //Judge whether the member element exists in the set key

SRANDMEMBER key [count]  //Randomly select count elements from the set key, and the elements will not be deleted

SPOP key [count]  //Select the count element from the set key and delete it

SINTER key [key...]  //Intersection operation

SINTERSTORE destination key [key...]  //The intersection operation result is saved in destination

SUNION key [key...] //Union operation

SUNIONSTORE destination key [key...] //Save union operation results to destination

SDIFF key [key...] //Difference set operation

SDIFFSTORE  destination key [key...] //Save the result of difference set operation to destination

Set application scenario

Wechat lottery applet

  • Click to participate in the lottery to join the collection
SADD key {userId}
  • View all users participating in the lottery
  • Draw count winners
SRANMEMBER key [count] /SPOP key [count]

Wechat likes, collects and labels

  • give the thumbs-up
SADD like:{news id} {user id}
  • Cancel like
SREM like:{news id} {user id}
  • Check whether the user likes it
SISMEMBER like:{news id} {user id}
  • Get the list of users who like
SMEMBERS like:{news id}
  • Number of users getting likes
SCARD like:{news id}

Collection operation to realize wechat attention model

  • Rookie concern cn
    cnSet {gcx,lfz,yhj}
  • People gcx cares about
    gcxSet {lfz,yhj,lf}
  • People yhj cares about
    yhjSet {lfz,gcx}
  • People I and gcx big V care about together
SINTER cnSet gcxSet    //The result is {lfz,yhj}
  • The people I pay attention to also pay attention to ta(yhj)
SISMEMBER lfzSet yhj

  • Someone I might know
SIDFF gcxSet cnSet  //The result is lf

Collection operation to realize e-commerce commodity screening

SADD brand:huawei P40

SADD brand:xiaomi mi-10

SADD brand:iPhone iphone10

SADD os:android P40 mi-10

SADD cpu:brand:intel P40 mi-10

SADD ram:8G P40 mi-10 iphone10
SINTER  os:android  cpu:brand:intel ram:8G   //The result is {P40 mi-10}

Zset ordered set

ZADD key score member [score memberr]  //Add elements with scores to the ordered set key of the net

ZREM key member [member]  //Delete element member from ordered collection

ZSCORE key member   //Returns the score of member in an ordered set

ZINCRBY key  increment member   //Add increment to the score of member

ZCARD key   //Returns the number of elements in the set key

ZRANGE key start stop [WITHSCORES]    //Get the elements from start to stop in the set key in positive order

ZREVRANGE key start stop [WITHSCORES]    //Get the elements from start to stop in the set key in reverse order

ZUNIONSTORE destkey numkeys key [key ...]  //Union operation

ZINTERSTORE destkey numkeys key [key ...]  //Intersection operation

Zset application scenario

Zset set implementation Leaderboard

  • Click news
ZINCRBY hotNews:20190819 1  Guard Hong Kong
  • Top ten on display day
ZREVRANGE hotNews:20190819 0 9 WITHSCORES
  • Show the top ten in seven days
ZREVRANGE hotNews:20190813-20190819 0 9 WITHSCORES

Keywords: Redis

Added by helpmeplease2 on Tue, 08 Feb 2022 23:44:01 +0200