Redis learning notes

Redis is a NoSQL Not Only SQL (key value)

NoSQL

Used to solve 3v+3 high

  • Massive Volume, real-time Velocity, diversity
  • High concurrency, high scalability and high performance

Redis Download

Windows

Download the zip package and unzip it to the environment folder

Linux

I use the automatic installation of pagoda panel

Directory for automatic installation

The running files and test files are under src

You can start redis cli

Redis performance test

redis-benchmark

Run redis benchmark

[root@hzf src]# ./redis-benchmark -c 100 -n 100000 -h 127.0.0.1 -p 6379

Front/ Very important, otherwise an error will be reported

-bash: redis-benchmark: command not found

After operation

redis default port 6379

redis has 16 databases (0 ~ 15) by default

You can switch databases through select

All key s in the database can be displayed

Empty the current database

Empty all databases

View current database size

Both quit and exit can exit redis

redis is single threaded

  • Myth 1: high performance database must be multi-threaded?

no

  • Myth 2: is multithreading faster than single thread?

CPU > memory > hard disk

redis is written in c language

Under multithreading, the cpu will switch context. redis is based on memory operation. cpu is not its performance bottleneck. It is the fastest under single thread

The bottleneck of redis is memory and network bandwidth

Five data types

Redis is an open source (BSD licensed) data structure server with in memory storage, which can be used as database, cache and message queue agent. It supports character string,Hashtable ,list,aggregate,Ordered setbitmap hyperloglogs And other data types. Built in replication Lua script , LRU retraction affair And different levels of disk persistence. At the same time, high availability is provided through Redis Sentinel and automatic storage is provided through Redis Cluster partition.

Redis-key

command describe
Redis Type command Returns the type of the value stored by the key.
Redis PEXPIREAT command Set the expiration time of the key in milliseconds.
Redis PEXPIREAT command Set the time stamp of key expiration time (unix timestamp) in milliseconds
Redis Rename command Modify the name of the key
Redis PERSIST command Remove the expiration time of the key, and the key will be persistent.
Redis Move command Move the key of the current database to the given database db.
Redis RANDOMKEY command Randomly return a key from the current database.
Redis Dump command Serialize the given key and return the serialized value.
Redis TTL command Returns the TTL (time to live) of a given key in seconds.
Redis Expire command seconds sets the expiration time for the given key.
Redis DEL command This command is used to delete a key when it exists.
Redis Pttl command Returns the remaining expiration time of the key in milliseconds.
Redis Renamenx command Change the name of the key to newkey only if the newkey does not exist.
Redis EXISTS command Check whether the given key exists.
Redis Expireat command The function of EXPIREAT is similar to that of EXPIRE. Both of them are used to set the expiration time for the key. The difference is that the time parameter accepted by the EXPIREAT command is UNIX timestamp.
Redis Keys command Find all patterns that match the given pattern key.
127.0.0.1:6379> set name hzf #Set key value
OK
127.0.0.1:6379> get name 
"hzf"
127.0.0.1:6379> EXISTS name #Judge whether there is this key, return 1 if there is one, and return 0 if there is none
(integer) 1
127.0.0.1:6379> EXISTS name1
(integer) 0
127.0.0.1:6379> EXPIRE name 10 #Set the expiration time of the key, in seconds
(integer) 1
127.0.0.1:6379> ttl name #Remaining lifetime of key
(integer) 6
127.0.0.1:6379> ttl name
(integer) 0
127.0.0.1:6379> ttl name #-2 indicates that the key does not exist
(integer) -2
127.0.0.1:6379> get name
(nil)
######################################################################
127.0.0.1:6379> set name hzf
OK
127.0.0.1:6379> set age 18
OK
127.0.0.1:6379> keys * #Get all key s of the current database
1) "age"
2) "name"
127.0.0.1:6379> type name #Determine the type of the key
string
127.0.0.1:6379> type age
string

String

command describe
Redis Setnx command The key value can only be set when the key does not exist.
Redis Getrange command Returns the sub character of the string value in the key
Redis Mset command Set one or more key value pairs at the same time.
Redis Setex command Associate the value value with the key and set the expiration time of the key to seconds (in seconds).
Redis SET command Set the value of the specified key
Redis Get command Gets the value of the specified key.
Redis Getbit command For the string value stored by key, obtain the bit on the specified offset.
Redis Setbit command For the string value stored by key, set or clear the bit on the specified offset.
Redis Decr command Subtract the numeric value stored in the key by one.
Redis Derby command key subtracts the given decrement from the stored value.
Redis Strlen command Returns the length of the string value stored by the key.
Redis Msetnx command Set one or more key value pairs at the same time if and only if all given keys do not exist.
Redis Incrby command Add the value stored by the key to the given increment value.
Redis Incrbyfloat command Add the value stored by the key to the given floating-point increment value.
Redis Setrange command Overwrite the string value stored by the given key with the value parameter, starting from the offset.
Redis Psetex command This command is similar to the SETEX command, but it sets the lifetime of the key in milliseconds instead of seconds, as the SETEX command does.
Redis Append command If the key already exists and is a string, the APPEND command appends value to the end of the original value of the key.
Redis Getset command Set the value of the given key to value and return the old value of the key.
Redis Mget command Gets the value of all (one or more) given key s.
Redis Incr command Increment the numeric value stored in the key by one.
127.0.0.1:6379> set city wuhan
OK
127.0.0.1:6379> get city
"wuhan"
127.0.0.1:6379> append city hp #Add characters after the value of the key to return the length of value
(integer) 7
127.0.0.1:6379> get city
"wuhanhp"
127.0.0.1:6379> strlen city #Gets the length of the value of the key
(integer) 7
######################################################################
127.0.0.1:6379> set views 0
OK
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> incr views #+ 1 per execution
(integer) 1
127.0.0.1:6379> incr views
(integer) 2
127.0.0.1:6379> get views
"2"
127.0.0.1:6379> decr views #- 1 per execution
(integer) 1
127.0.0.1:6379> decr views
(integer) 0
127.0.0.1:6379> decr views
(integer) -1
127.0.0.1:6379> incrby views 10 #You can set the increased step size
(integer) 9
127.0.0.1:6379> get views
"9"
127.0.0.1:6379> decrby views 5 #You can set the reduced step size
(integer) 4
######################################################################
127.0.0.1:6379> set key2 0123456789
OK
127.0.0.1:6379> getrange key2 2 5 #You can get the string range of indexes 2-5
"2345"
127.0.0.1:6379> setrange key2 3 xxx #Replace (modify) from the place with index 3
(integer) 10
127.0.0.1:6379> get key2
"012xxx6789"
######################################################################
127.0.0.1:6379> setex name 20 hzf #You can set the expiration time of the key in seconds
OK
127.0.0.1:6379> ttl name #Used to check how long the key has expired, in seconds
(integer) 15
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> setnx name hhh #If the key is not set again, 0 will be returned, which means the setting fails
(integer) 1                    #Distributed meeting common
127.0.0.1:6379> setnx name zzz
(integer) 0
127.0.0.1:6379> get name
"hhh"
######################################################################
127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3 #Multiple k-v can be set at the same time
OK
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
3) "k1"
127.0.0.1:6379> mget k1 k2 k3 #v of multiple k can be obtained at the same time
1) "v1"
2) "v2"
3) "v3"
127.0.0.1:6379> mset k1 v1 k4 v4
OK
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
3) "k1"
4) "k4"
127.0.0.1:6379> msetnx k1 v1 k5 v5 #Atomic operations, both successful and failed
(integer) 0
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
3) "k1"
4) "k4"
######################################################################
#Save an object
#Common method, using json string
127.0.0.1:6379> set user:1 {name:abc,age:5}
OK
127.0.0.1:6379> get user
(nil)
127.0.0.1:6379> get user:1
"{name:abc,age:5}"
#key's ingenious design user: {ID}: {file} is supported in redis
127.0.0.1:6379> mset user:2:name cba user:2:age 3
OK
127.0.0.1:6379> mget user:2:name user:2:age
1) "cba"
2) "3"
######################################################################
#getset can get the V of this k first, if not, return nil, and then set a new v
127.0.0.1:6379> getset db redis 
(nil)
127.0.0.1:6379> get db
"redis"
127.0.0.1:6379> getset db mongDB
"redis"
127.0.0.1:6379> get db
"mongDB"

List

command describe
Redis Lindex command Get elements in the list by index
Redis Rpush command Add one or more values to the list
Redis Lrange command Gets the elements within the specified range of the list
Redis Rpoplpush command Removes the last element of the list, adds it to another list, and returns
BLIS redis command Move out and get the first element of the list. If there is no element in the list, the list will be blocked until the waiting timeout or pop-up element is found.
Redis Brpop command Move out and get the last element of the list. If there are no elements in the list, the list will be blocked until the waiting timeout or pop-up elements are found.
Redis Brpoplpush command Pop up a value from the list, insert the pop-up element into another list and return it; If there are no elements in the list, the list will be blocked until the wait times out or pop-up elements are found.
Redis Lrem command Remove list elements
Redis Llen command Get list length
Redis Ltrim command Trim a list, that is, make the list retain only the elements within the specified interval, and the elements not within the specified interval will be deleted.
Redis Lpop command Move out and get the first element of the list
Redis Lpushx command Inserts one or more values into the header of an existing list
Redis Linsert command Inserts an element before or after an element in the list
Redis Rpop command Remove and get the last element of the list
Redis Lset command Sets the value of a list element by index
Redis Lpush command Inserts one or more values into the list header
Redis Rpushx command Add a value to an existing list

List is like a large container. You can add modules from the left or right. You can play into stacks, queues, blocking queues...

The values in the List can be repeated

127.0.0.1:6379> lpush list A B C d #Add from the left to the list
(integer) 4
127.0.0.1:6379> lrange list 0 -1 #Get all elements in the list. 0 - 1 means all 
1) "d"
2) "C"
3) "B"
4) "A"
127.0.0.1:6379> rpush list aaa #Add from the right to the list 
(integer) 5
127.0.0.1:6379> lrange list 0 -1
1) "d"
2) "C"
3) "B"
4) "A"
5) "aaa"
127.0.0.1:6379> lrange list 0 2 #Get elements of index range 0 ~ 2
1) "d"
2) "C"
3) "B"
######################################################################
127.0.0.1:6379> lpop list #Pop up an element from the far left of the list
"d"
127.0.0.1:6379> rpop list #Pop up an element from the far right of the list
"aaa"
127.0.0.1:6379> lrange list 0 -1
1) "C"
2) "B"
3) "A"
######################################################################
127.0.0.1:6379> lindex list 1 #Gets the element corresponding to the index subscript
"B"
127.0.0.1:6379> lindex list 0
"C"
######################################################################
127.0.0.1:6379> llen list #Get the length of the list
(integer) 3
127.0.0.1:6379> lpush list dd
(integer) 4
127.0.0.1:6379> llen list
(integer) 4
######################################################################
127.0.0.1:6379> lrange list 0 -1
1) "A"
2) "dd"
3) "dd"
4) "dd"
5) "C"
6) "B"
7) "A"
127.0.0.1:6379> lrem list 1 A #Remove an A
(integer) 1
127.0.0.1:6379> lrange list 0 -1
1) "dd"
2) "dd"
3) "dd"
4) "C"
5) "B"
6) "A"
127.0.0.1:6379> lrem list 3 dd #Remove 3 dd
(integer) 3
127.0.0.1:6379> lrange list 0 -1
1) "C"
2) "B"
3) "A"
######################################################################
127.0.0.1:6379> lpush mylist hello hello1 hello2 hello3
(integer) 4
127.0.0.1:6379> lrange mylist 0 -1
1) "hello3"
2) "hello2"
3) "hello1"
4) "hello"
127.0.0.1:6379> ltrim mylist 1 2 #Intercepting the selected part actually changes the list
OK
127.0.0.1:6379> lrange mylist 0 -1
1) "hello2"
2) "hello1"
######################################################################
127.0.0.1:6379> lpush mylist hello
(integer) 1
127.0.0.1:6379> lpush mylist hello1
(integer) 2
127.0.0.1:6379> lpush mylist hello2
(integer) 3
127.0.0.1:6379> lrange mylist 0 -1
1) "hello2"
2) "hello1"
3) "hello"
#First pop up an element from mylist, and then put the pop-up element into myotherlist
127.0.0.1:6379> rpoplpush mylist myotherlist 
"hello"
127.0.0.1:6379> lrange mylist 0 -1
1) "hello2"
2) "hello1"
127.0.0.1:6379> lrange myotherlist 0 -1
1) "hello"
######################################################################
127.0.0.1:6379> lrange myotherlist 0 -1
1) "hello"
127.0.0.1:6379> lset myotherlist 0 ababab #You can modify the value of the specified subscript
OK
127.0.0.1:6379> lrange myotherlist 0 -1
1) "ababab"
######################################################################
127.0.0.1:6379> lrange mylist 0 -1
1) "hello2"
2) "hello1"
127.0.0.1:6379> linsert mylist before hello1 goin #Insert element before specifying element
(integer) 3
127.0.0.1:6379> lrange mylist 0 -1
1) "hello2"
2) "goin"
3) "hello1"
127.0.0.1:6379> linsert mylist after goin outin #Inserts an element after the specified element
(integer) 4
127.0.0.1:6379> lrange mylist 0 -1
1) "hello2"
2) "goin"
3) "outin"
4) "hello1"

Set

command describe
Redis Sunion command Returns the union of all given sets
Redis scar command Gets the number of members of the collection
Redis Srandmember command Returns one or more random numbers in a collection
Smembers command Returns all members of the collection
Redis Sinter command Returns the intersection of all given sets
Redis Srem command Remove one or more members from the collection
Redis Smove command Move the member element from the source collection to the destination collection
Redis Sadd command Add one or more members to the collection
Redis Sismember command Judge whether the member element is a member of the set key
Redis Sdiffstore command Returns the difference set of all given sets and stores it in destination
Redis Sdiff command Returns the difference set of all given sets
Redis Sscan command Iterating over elements in a collection
Redis Sinterstore command The intersection of a given set of destinations and returns all of them in the set of destinations
Redis Sunionstore command The union of all given sets is stored in the destination set
Redis Spop command Removes and returns a random element in the collection

The value in set cannot be repeated

127.0.0.1:6379> sadd myset hi #Add element to set
(integer) 1
127.0.0.1:6379> sadd myset hi1
(integer) 1
127.0.0.1:6379> sadd myset hi2
(integer) 1
127.0.0.1:6379> sadd myset hi3
(integer) 1
127.0.0.1:6379> smembers myset #View all elements in set
1) "hi"
2) "hi3"
3) "hi2"
4) "hi1"
127.0.0.1:6379> sismember myset hi2 #Check whether the corresponding element exists in the corresponding k
(integer) 1                         #Returns 1 if it exists and 0 if it does not exist
127.0.0.1:6379> sismember myset haha
(integer) 0
127.0.0.1:6379> scard myset #Gets the length of the collection
(integer) 4
127.0.0.1:6379> srem myset hi1 hi3 #Removes the specified element from the collection
(integer) 2
127.0.0.1:6379> smembers myset
1) "hi"
2) "hi2"
######################################################################
127.0.0.1:6379> smembers myset
1) "hi7"
2) "hi"
3) "hi2"
4) "hi3"
5) "hi1"
6) "hi5"
7) "hi4"
8) "hi6"
127.0.0.1:6379> srandmember myset #Randomly gets the specified number of elements in the collection
"hi3"
127.0.0.1:6379> srandmember myset
"hi"
127.0.0.1:6379> srandmember myset
"hi"
127.0.0.1:6379> srandmember myset 2
1) "hi4"
2) "hi2"
######################################################################
127.0.0.1:6379> smembers myset
1) "hi7"
2) "hi"
3) "hi2"
4) "hi3"
5) "hi1"
6) "hi5"
7) "hi4"
8) "hi6"
127.0.0.1:6379> spop myset #Randomly pop up a specified number of elements from the collection
"hi4"
127.0.0.1:6379> spop myset
"hi"
127.0.0.1:6379> smembers myset
1) "hi7"
2) "hi2"
3) "hi3"
4) "hi1"
5) "hi5"
6) "hi6"
127.0.0.1:6379> spop myset 2
1) "hi2"
2) "hi3"
######################################################################
127.0.0.1:6379> sadd myset h1 h2 h3 h4 h5 
(integer) 5
127.0.0.1:6379> smembers myset
1) "h3"
2) "h2"
3) "h4"
4) "h1"
5) "h5"
#Transfers a specified element from one collection to another
127.0.0.1:6379> smove myset otherset h1 
(integer) 1
127.0.0.1:6379> smembers myset
1) "h2"
2) "h4"
3) "h3"
4) "h5"
127.0.0.1:6379> smembers otherset
1) "h1"
######################################################################
127.0.0.1:6379> sadd k1 a b c d
(integer) 4
127.0.0.1:6379> sadd k2 c d e f
(integer) 4
127.0.0.1:6379> sdiff k1 k2 #Difference set
1) "a"
2) "b"
127.0.0.1:6379> sdiff k2 k1
1) "f"
2) "e"
127.0.0.1:6379> sinter k1 k2 #intersection #Common friends can be achieved in this way
1) "d"
2) "c"
127.0.0.1:6379> sunion k1 k2 #Union
1) "c"
2) "f"
3) "a"
4) "d"
5) "b"
6) "e"

Hash

command describe
Redis Hmset command Set multiple field value pairs into the hash table key at the same time.
Redis Hmget command Gets the value of all the given fields
Redis Hset command Set the value of the field field in the hash table key to value.
Redis Hgetall command Gets all fields and values of the specified key in the hash table
Redis Hget command Get the value of the specified field stored in the hash table / td >
Redis Hexists command Check whether the specified field exists in the hash table key.
Redis Hincrby command Add increment to the integer value of the specified field in the hash table key.
Redis Hlen command Gets the number of fields in the hash table
Redis Hdel command Delete one or more hash table fields
Redis Hvals command Gets all the values in the hash table
Redis Hincrbyfloat command Add increment to the floating-point value of the specified field in the hash table key.
Redis Hkeys command Gets the fields in all hash tables
Redis Hsetnx command Set the value of the hash table field only if the field field does not exist.

It is equivalent to HashMap (key map)

Essentially, it is similar to string. It is a simple key value pair

hash is more suitable for accessing objects and string is suitable for accessing characters

127.0.0.1:6379> hset myhash f1 hzf #Add element
(integer) 1
127.0.0.1:6379> hget myhash f1 #Get element
"hzf"
127.0.0.1:6379> hmset myhash f1 hello f2 world #Add multiple elements at the same time
OK
127.0.0.1:6379> hmget myhash f1 f2 #Get multiple elements at the same time
1) "hello"
2) "world"
127.0.0.1:6379> hgetall myhash #If you get all the elements, it will display the form of k above and v below
1) "f1"
2) "hello"
3) "f2"
4) "world"
127.0.0.1:6379> hdel myhash f1 #Delete the specified map
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "f2"
2) "world"
127.0.0.1:6379> hlen myhash #Gets the number of fields in the specified hash
(integer) 1
127.0.0.1:6379> hexists myhash f1 #Judge whether the specified map exists in the hash
(integer) 0
127.0.0.1:6379> hexists myhash f2
(integer) 1
######################################################################
127.0.0.1:6379> hmset myhash h1 m1 h2 m2 h3 m3 h4 m4
OK
127.0.0.1:6379> hkeys myhash #Get all key s of fields in hash
1) "h1"
2) "h2"
3) "h3"
4) "h4"
127.0.0.1:6379> hvals myhash #Get all value s of fields in hash
1) "m1"
2) "m2"
3) "m3"
4) "m4"
######################################################################
127.0.0.1:6379> hset myhash age 5
(integer) 1
127.0.0.1:6379> hincrby myhash age 3 #Specified field increase
(integer) 8
127.0.0.1:6379> hincrby myhash age -5
(integer) 3
127.0.0.1:6379> hsetnx myhash name hzf #If there is none, the addition succeeds, and if there is one, the addition fails
(integer) 1
127.0.0.1:6379> hsetnx myhash name hzf
(integer) 0

Zset (ordered set)

command describe
Redis Zrevrank command Returns the ranking of the specified members in the ordered set. The members of the ordered set are sorted by decreasing points (from large to small)
Redis Zlexcount command Calculates the number of members in the specified dictionary interval in an ordered set
Redis Zunionstore command Calculate the union of one or more given ordered sets and store them in a new key
Redis Zremrangebyrank command Removes all members of a given ranking interval from an ordered set
Redis Zcard command Gets the number of members of an ordered collection
Redis Zrem command Remove one or more members from an ordered collection
Redis Zinterstore command Calculate the intersection of one or more given ordered sets and store the result set in the new ordered set key
Redis Zrank command Returns the index of a specified member in an ordered collection
Redis Zincrby command Adds an increment to the score of a specified member in an ordered set
Redis Zrangebyscore command Returns the members in the specified interval of an ordered set through scores
Redis Zrangebylex command Returns the members of an ordered set through a dictionary interval
Redis Zscore command Returns the score value of a member in an ordered set
Redis Zremrangebyscore command Removes all members of a given score interval from an ordered set
Redis Zscan command Iterate the elements in the ordered set (including element members and element scores)
Redis Zrevrangebyscore command Returns the members within the specified score range in the ordered set. The scores are sorted from high to low
Redis Zremrangebylex command Removes all members of a given dictionary interval from an ordered set
Redis Zrevrange command Returns the members in the specified interval in the ordered set. Through the index, the score is from high to low
Redis Zrange command The ordered set is returned through the index interval to synthesize the members in the specified interval
Redis Zcount command Calculates the number of members of a specified interval score in an ordered set
Redis Zadd command Add one or more members to an ordered collection, or update the scores of existing members

Three special types

Geospatial (geographical location)

command describe
Redis GEOHASH command Returns a Geohash representation of one or more location elements
Redis GEOPOS command Return the positions (longitude and latitude) of all the given positioning elements from the key
Redis GEODIST command Returns the distance between two given positions
Redis GEORADIUS command Take the given latitude and longitude as the center to find out the elements within a certain radius
Redis GEOADD command Add the specified geospatial location (longitude, latitude, name) to the specified key
Redis GEORADIUSBYMEMBER command Find the element within the specified range. The center point is determined by the given location element

The effective longitude is from - 180 degrees to 180 degrees.

The effective latitude ranges from -85.05112878 degrees to 85.05112878 degrees.

When the coordinate position exceeds the above specified range, the command will return an error.

127.0.0.1:6379> geoadd China:city 168.1 34.5 Hongkong
(integer) 1
127.0.0.1:6379> geoadd China:city 123.5 24.8 Chongqing #Add position latitude and longitude
(integer) 1
127.0.0.1:6379> geodist China:city Hongkong Chongqing km #Distance between two positions
"4407.0582"
127.0.0.1:6379> georadius China:city 168 33 400 km #Specify the points that exist within the coordinate range
1) "Hongkong"
127.0.0.1:6379> georadius China:city 168 33 400 km withcoord #With latitude and longitude
1) 1) "Hongkong"
   2) 1) "168.10000151395797729"
      2) "34.49999971716130887"
127.0.0.1:6379> georadius China:city 168 33 400 km withdist #Belt distance
1) 1) "Hongkong"
   2) "167.0955"
127.0.0.1:6379> geopos China:city Hongkong #Gets the latitude and longitude of the specified point
1) 1) "168.10000151395797729"
   2) "34.49999971716130887"

HyperLogLog

command describe
Redis Pfmerge command Merge multiple hyperlogs into one hyperlog
Redis Pfadd command Adds the specified element to the hyperlog.
Redis Pfcount command Returns the cardinality estimate for a given hyperlog.

The hyperlog type is used to count the cardinality (non repeated number). It is suitable for counting the number of active users (not user id). There will be an error of about 0.81%, so it is not suitable for scenes requiring high precision. The occupied memory is fixed at 12kb, which is very small

127.0.0.1:6379> pfadd myset a b c d e #Add element
(integer) 1
127.0.0.1:6379> pfadd myset1 d e f g 
(integer) 1
127.0.0.1:6379> pfcount myset #Count the number of non repeating elements
(integer) 5
127.0.0.1:6379> pfcount myset1
(integer) 4
127.0.0.1:6379> pfcount myset myset1
(integer) 7
#Put the non repeating elements in set and set1 into set3
127.0.0.1:6379> pfmerge myset3 myset myset1 
OK
127.0.0.1:6379> pfcount myset3
(integer) 7

Bitmap

Bitmap is bit storage, which is used to count user information, such as login or not login, clock in or not clock in... And can be stored in only two states, only 0 and 1

365 days = 365bit, 1 byte = 8bit, so the memory occupied is very small

#Punch in test
127.0.0.1:6379> setbit 2020 0 0 #Set no sign in on the first day
(integer) 0
127.0.0.1:6379> setbit 2020 1 1 #Check in the next day
(integer) 0
127.0.0.1:6379> setbit 2020 2 1
(integer) 0
127.0.0.1:6379> setbit 2020 3 1
(integer) 0
127.0.0.1:6379> setbit 2020 4 0
(integer) 0
127.0.0.1:6379> getbit 2020 0 #Check in on the first day
(integer) 0
127.0.0.1:6379> getbit 2020 1
(integer) 1
127.0.0.1:6379> getbit 2020 3
(integer) 1
127.0.0.1:6379> getbit 2020 2
(integer) 1

Redis transaction

Essence of redis transaction: a set of commands. All commands in a transaction will be serialized and executed sequentially during transaction execution

For example, Mysql transactions comply with the ACID (atomicity, consistency, isolation and persistence) principle, but redis is different. Redis transactions can be summarized as one-time, sequential and exclusive

Redis transactions do not have the concept of isolation level

Commands are executed one by one in the queue, and only those that are not initiated are executed directly

Redis single command keeps atomicity, but transactions do not guarantee atomicity

  • redis transaction execution sequence:

    • Open transaction
    • Order to join the team
    • Execute transaction

redis can realize optimistic lock and watch (monitor)

command describe
Redis Exec command Execute commands within all transaction blocks.
Redis Watch command Monitor one (or more) keys. If this (or these) key is changed by other commands before the transaction is executed, the transaction will be interrupted.
Redis Discard command Cancel the transaction and abort all commands in the transaction block.
Redis Unwatch command Cancel the monitoring of all key s by the WATCH command.
Redis Multi command Mark the beginning of a transaction block.

Normal execution

127.0.0.1:6379> multi #Open transaction
OK
127.0.0.1:6379> set k1 v1 #Order to join the team
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> get k2
QUEUED
127.0.0.1:6379> exec #Execute the order to join the team in turn
1) OK
2) OK
3) OK
4) "v2"

Abandon transaction

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> discard #Abandon the transaction and all commands will not be executed
OK
127.0.0.1:6379> get k1
(nil)
127.0.0.1:6379> get k2
(nil)
127.0.0.1:6379> get k3
(nil)

Compiled exception (code error), all commands in the transaction will not be executed

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> getset k4
(error) ERR wrong number of arguments for 'getset' command
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> set k5 v5
QUEUED
127.0.0.1:6379> exec #The upper part reports an error, and all of them fail directly
(error) EXECABORT Transaction discarded because of previous errors.

Run time exception (such as 1 / 0). The wrong command will not be executed, but the correct command will be executed

127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> incr k1
QUEUED
127.0.0.1:6379> set k2 v2 
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> exec
1) (error) ERR value is not an integer or out of range #Wrong execution failed
2) OK #The correct command is executed normally
3) OK
127.0.0.1:6379> get k1
"v1"
127.0.0.1:6379> get k2
"v2"
127.0.0.1:6379> get k3
"v3"

Optimistic lock

  • Pessimistic lock: very pessimistic. I think there will be problems at any time. No matter what I do, I lock it, which is inefficient

  • Optimistic lock: I don't think there will be any problem at any time, so I don't lock it. I only judge whether someone has modified the data during the update

    • Get version
    • Compare version when updating

Normal operation

127.0.0.1:6379> set money 100
OK
127.0.0.1:6379> set out 0
OK
127.0.0.1:6379> watch money #Monitoring money is equivalent to locking operation. It will judge whether it changes after it is completed
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 20
QUEUED
127.0.0.1:6379> incrby out 20
QUEUED
127.0.0.1:6379> exec
1) (integer) 80
2) (integer) 20

Two threads, one of which is in operation, and the other is modified by queue jumping, will lead to transaction execution failure

127.0.0.1:6379> watch money
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 20
QUEUED
127.0.0.1:6379> incrby out 20
QUEUED
127.0.0.1:6379> exec
1) (integer) 80
2) (integer) 20
127.0.0.1:6379> watch money
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 10
QUEUED
127.0.0.1:6379> incrby out 10
QUEUED
127.0.0.1:6379> exec
(nil)
127.0.0.1:6379> get money #The transaction execution failed, but the command of another thread was executed successfully
"200"
127.0.0.1:6379> unwatch #Unlock 
OK
127.0.0.1:6379> watch money #Monitor updated data
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 50
QUEUED
127.0.0.1:6379> incrby out 50
QUEUED
127.0.0.1:6379> exec #If the data is not updated, the execution is successful, otherwise it will be repeated from unwatch
1) (integer) 150
2) (integer) 70
######################################################################
127.0.0.1:6379> get money
"80"
127.0.0.1:6379> set money 200
OK

Tags: Database Redis

Posted by ChrisBoden on Sun, 15 May 2022 10:01:55 +0300