Introduction and command of Redis -- crazy God Theory

You can search Redis on bilibili to learn videos (crazy God said)

Getting started with Redis

summary
Official website: https://redis.io/
Chinese website: https://www.redis.cn/
Redis (Remote Dictionary Server), i.e. remote dictionary service. It is an open source log and key value database written in ANSI C language, supporting network, memory based and persistent, and provides API s in multiple languages.
redis periodically writes the updated database to disk or writes the modification operation to the additional record file, and realizes master-slave synchronization on this basis.
The author of redis, Salvatore Sanfilippo, comes from Sicily, Italy and lives in Catania. Currently working for pivot. The net name he uses is antirez.
Common commands:
TYPE key - used to obtain the type of a key
KEYS pattern - matches all KEYS that match the pattern. For example, KEYS * lists all KEYS. Of course, the complexity is O(n)
Random key - returns a random key
RENAME oldkeynewkey - the key can also be renamed
List operation, essence
RPUSH key string - adds a value to the end of a key list
LPUSH key string - adds a value to the header of a key list
LLEN key - list length
LRANGE key start end - returns the value of a range in the list, which is equivalent to the paging query in mysql
LTRIM key start end - keep only the value of a range in the list
LINDEX key index - gets the value of a specific index number in the list. Note the O(n) complexity
LSET key index value - sets the value of a position in the list
LPOP key
RPOP key - like LPOP above, it is a header and tail instruction similar to stack or queue, which can be used as a message queue
Collection operation
SADD key member - add element
SREM key member -- delete element
Scar key -- returns the size of the collection
SIS member key member - determines whether a value is in the collection
Sinter key1, key2... keyN -- get the intersection elements of multiple sets
SMEs key - lists all elements of the collection
There is also the command of Multiple DB, which can replace db and isolate data. It is stored in DB 0 by default
What can Redis do
1. Memory storage, persistence, and event breakpoints in memory are lost, so persistence is very important (rdb, aof)
2. Efficient and can be used for caching
3. Publish subscribe system
4. Map information analysis
5. Timer, counter (Views)
6, ......
characteristic
1. Diverse data types
2. Persistence
3. Cluster
4. Business
5, ......
Download address: under download on the official website

install

Windows setup

1. Go to Github to download
2. Copy the downloaded package to the directory of the configuration environment and unzip it
3. Open redis and double-click to run redis-server.exe. The default port number is 6379
4. Use the redis client to connect to redis. Double click redis-cli.exe. Enter the command: ping
Seeing the output POMG indicates that the connection is successful

Linux Installation

I haven't used XShell for a long time. I found that the evaluation period has passed

Solution: first uninstall the charged version and install the free version
1) Log in to the download page on the official website of NetSarang (xshell developer) and log in to QQ email in advance:
https://www.netsarang.com/zh/free-for-home-school/

2) Click download to pop up this page

3) QQ email will receive the download link

Wait for the download to complete, then click Install

  1. After installation, a new session will pop up directly. Just create a new session directly.
    The host in the new session can fill in the on the virtual machine, open the virtual machine, select any connection, and enter ifconfig to view

Copy the ip address above and paste it on the host in the new session

Click on the connection and a message will appear. If you click OK, don't worry. Just click again in the newly created session, and an SSH security warning will pop up

Pop up a safety warning like this

Click accept and save directly. The following situation will appear. Select Yes or no

If you click Yes, you will download the page

Jump to the page and fill in the information

  1. Install Xftp7. After downloading, directly click Install to complete the installation.
    Tip: the above is just to solve the urgent problem, because this is only a 30 day evaluation period. Once the evaluation period is over, a pop-up window will pop up asking you to buy. After the above steps are completed, install redis
    1. Download the installation package directly on the official website. After downloading, open xshell and click xftp

Directly find the downloaded redis on the left and drag it to the right

If you are in drive C, you cannot enter the root directory

Open the VMware virtual machine, connect the terminal, enter ifconfig, and find the ip address

Copy it, open cmd on the computer, enter ping 192.168.12.128, and continue to run until 0% is lost

Then you go to the Xshell to create a new session

At this point, you can see that you have entered root. At this time, the cd enters the home directory, and then enters the newly created directory in xftp. ls lists all the files. You can see that redis is uploaded successfully

In addition, after Xftp is connected to the virtual machine, there are friends with garbled code. Please stamp
https://blog.csdn.net/Yao1100000/article/details/109095042 That is, select UTF-8 in xftp – file – properties – options – encoding
Note: if you want to enter root later, you must first open the virtual machine and start the virtual machine
2. Unzip the Redis installation package. This is a program, so it is usually placed in the / opt directory and moved to rm redis-6.2.4.tar.gz /opt

3. Unzip, tar -zxvf redis-6.2.4.tar.gz

4. After decompression, you can cd redis-6.2.4 and then ls view it

5. Install GCC (basic environment), yum install gcc-c + +. Run to the back and ask you to confirm whether to install it (there are two queries). Just confirm. After the installation is completed, enter gcc -v to see if it can be used

Then enter the make command, but if you have not installed a package that supports the make command, you will be prompted whether to install it. Just confirm. Make after installation. To view the installation, execute make install

6. The default installation path of redis is / usr/local/bin

7. Create a new directory mkdir redisconfig and copy the conf directory under redis to the redisconfig folder
cp /opt/redis-6.2.4/redis.conf redisconfig

8. redis is not started in the background by default. The configuration needs to be modified.

vim redis.conf find daemonize take no Change to yes
 Press i Enter insert (Edit) mode
 Press esc Then enter:wq(Save file, exit vim (command)
:w(Save the file without exiting vim (command)
:q!(Force exit without saving file vim (command)

9. Start redis service
pwd is the abbreviation of print working directory. Printing the current working directory means displaying the current directory

But in fact, this is the start
10. Use the Linux client to connect. Enter redis cli - P 6379
keys * view all key s in the database

11. View the redis process ps -ef|grep redis

ps Command displays a process
grep The command is find
 middle|Is the pipe command ps Command and grep Simultaneous execution
PS yes LINUX The most commonly used and powerful process view command

12. Shut down the redis service and exit

Test performance
Redis benchmark, the official performance testing tool, is a stress testing tool

test

#100 concurrent connections 100000 requests
#The default port number of redis connecting to the local (127.0.0.1), 100 concurrent connections, 100000 requests, -q forced to quit redis
redis-benchmark -h localhost -p 6379 -c 100 -n 100000 -q


Basic knowledge

Redis has 16 databases by default. The 0 database is used by default

You can use select to switch

If you write a value to the database, it is only in 4 this database, which is not related to other databases. That is, different databases can store different values
clear database

flushdb Empty current library
flushall Empty all database contents

Redis port number 6379 has a history, as well as MySQL default port number 3306
Redis is single threaded
Redis is fast. Officials say that redis is based on memory operation, and CPU is not redis's performance bottleneck. Redis's bottleneck is based on the machine's memory and network bandwidth. Since it can be implemented by single thread, single thread is used
Redis is written in C language. The official data provided is 100000 + QPS, which is no worse than Memecache, which also uses key value.
Why is Redis single thread so fast
1. Myth 1: high performance servers must be multi-threaded
2. Myth 2: multithreading (CPU context switching) must be more efficient than single thread
To understand the speed of CPU, memory and hard disk, CPU > memory > hard disk
Core: redis places all data in memory, so the efficiency of using single thread to operate is the highest. Multithreading (CPU context switching: time-consuming operation). For the memory system, if there is no context switching, the efficiency is the highest. Multiple reads and writes are on the same CPU. In memory, this is the best solution

Five data types

Redis-Key

First, connect redis to ensure that the client and server are connected

127.0.0.1:6379> flushall  #Clear all data
OK
127.0.0.1:6379> set name changan #set a key
OK
127.0.0.1:6379> keys *  #View all key s
1) "name"
127.0.0.1:6379> set age 18
OK
127.0.0.1:6379> keys *
1) "name"
2) "age"
127.0.0.1:6379> exists name  # Judge whether the current key exists
(integer) 1	#Return 1 to prove existence
127.0.0.1:6379> exists name1
(integer) 0
127.0.0.1:6379> move name 1  #Remove current key
(integer) 1
127.0.0.1:6379> keys *
1) "age"
127.0.0.1:6379> set name gucheng
OK
127.0.0.1:6379> keys *
1) "name"
2) "age"
127.0.0.1:6379> get name
"gucheng"
127.0.0.1:6379> expire name 10  #Set the expiration time of the key. The unit is s
(integer) 1
127.0.0.1:6379> ttl name  #Check the overdue progress. If it is - 2, it proves that the above 10s has passed
(integer) 1	   # 1 means it will expire in 1s
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> set name gucheng
OK
127.0.0.1:6379> keys *
1) "name"
2) "age"
127.0.0.1:6379> type name  #View the type of current key
string
127.0.0.1:6379> type age
string
127.0.0.1:6379>
String(character string)
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> set key1 v1	  #Set value
OK
127.0.0.1:6379> get key1    #Get value
"v1"
127.0.0.1:6379> keys *   #Get all key s 
1) "key1"
127.0.0.1:6379> exists key1   #Determine whether a key exists
(integer) 1
127.0.0.1:6379> append key1 "china"	#Append a string. If the current key does not exist, it is equivalent to set ting a key
(integer) 7
127.0.0.1:6379> get key1
"v1china"
127.0.0.1:6379> strlen key1  #Gets the length of the string
(integer) 7
127.0.0.1:6379> append key1 ",cidu"
(integer) 12
127.0.0.1:6379> get key1
"v1china,cidu"
###########################
# i + + step i+=
# set title:100:views 0  #Set the page views of the 100th article of the title to 0
127.0.0.1:6379> set views 0  #The initial number of views is 0
OK
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> incr views  #Self increasing 1 views + 1
(integer) 1
127.0.0.1:6379> get views
"1"
127.0.0.1:6379> decr views  #Self minus 1 views - 1
(integer) 0
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> incrby views 9  #You can set the step size and specify the increment (add 9 pieces of data at a time)
(integer) 9
127.0.0.1:6379> decrby views 2  #Reduce 2 pieces of data at a time
(integer) 7
################################
# String range
127.0.0.1:6379> set key1 "vigorous,life"  #Set key1 value
OK
127.0.0.1:6379> get key1
"vigorous,life"
127.0.0.1:6379> getrange key1 1 5  #Intercept string from [1,5] length
"igoro"
127.0.0.1:6379> getrange key1 0 -1  #Getting all strings is the same as getting key
"vigorous,life"

#### replace
127.0.0.1:6379> set key2 beautiful  
OK
127.0.0.1:6379> get key2
"beautiful"
127.0.0.1:6379> SETRANGE key2 3 xxx   #Replace the string starting at the specified position, and the index starts at 0
(integer) 9
127.0.0.1:6379> get key2
"beaxxxiful"
################################
# setex (set with expire) sets the expiration time. setnx (set with not exist) sets a value that does not exist (often used in distributed locks)
127.0.0.1:6379> get key2 "beaxxiful"
127.0.0.1:6379> setex key3 25 "guangzhou"  #Set the value of key3 to guangzhou and expire in 25 seconds
OK
127.0.0.1:6379> ttl keys
(integer) -2
127.0.0.1:6379> get key3
(nil)
127.0.0.1:6379> setnx indexkey "redis"  #If the indexkey does not exist, create an indexkey
(integer) 1
127.0.0.1:6379> setnx indexkey "shenzhen"  #If the indexkey exists, the creation fails
(integer) 0	#Return 0 description creation failed
127.0.0.1:6379> get indexkey
"redis"
################################
# mset  mget
127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3  #Set multiple values at the same time
OK
127.0.0.1:6379> keys *
1) "k3"
2) "k1"
3) "k2"
127.0.0.1:6379> mget k1 k2 k3  #Get multiple values at the same time
1) "v1"
2) "v2"
3) "v3"
127.0.0.1:6379> msetnx k1 v1 k7 v7   # msetnx is an atomic operation that either succeeds or fails
(integer) 0	#Failed to return 0 description
127.0.0.1:6379> get k7
(nil)
#object
set user:1{name:Guangdong,age:600}    #Set a user:1 object with the value of json character to save an object
# The key design here is user: {ID}: {file} (attribute). This design is completely OK in Redis
127.0.0.1:6379> mset user:1:name gaungdong user:1:age 600
OK
127.0.0.1:6379> mget user:1:name user:1:age
1) "gaungdong"
2) "600"
################################
# getset     #First get and then set
127.0.0.1:6379> getset sys redis  #nil if no value exists
(nil)
127.0.0.1:6379> get sys
"redis"
127.0.0.1:6379> getset sys studentsys  #If a value exists, get the original value and set a new value
"redis"
127.0.0.1:6379> get sys
"studentsys"

String similar usage scenario: value can be a number in addition to a string

  • Counter
  • Count multi unit quantity
  • Number of fans
  • Object cache storage

List

Basic data types, lists
In Redis, you can play list s as stacks, columns, and blocking queues
All list commands begin with l

127.0.0.1:6379> lpush list Guangzhou  #Insert one or more values into the head of the list (left)
(integer) 1
127.0.0.1:6379> lpush list shenzhen
(integer) 2
127.0.0.1:6379> lpush list foshan
(integer) 3
127.0.0.1:6379> lrange list 0 -1   #Get the value in the list
1) "foshan"
2) "shenzhen"
3) "guangzhou"
127.0.0.1:6379> lrange list 1 2  #Obtain the specific value through the interval
1) "shenzhen"
2) "guangzhou"
127.0.0.1:6379> rpush list donggaun  #Insert one or more values at the end of the list (right)
(integer) 4
127.0.0.1:6379> lrange list 0 -1
1) "foshan"
2) "shenzhen"
3) "guangzhou"
4) "donggaun"
############################
#pop, remove
127.0.0.1:6379> lpop list  #Remove the first element of the list
"foshan"
127.0.0.1:6379> rpop list  #Remove the last element of the list
"donggaun"
127.0.0.1:6379> lrange key 0 -1
(empty array)
127.0.0.1:6379> lrange list 0 -1
1) "shenzhen"
2) "guangzhou"
############################
# lindex
127.0.0.1:6379> lindex list 1  #Get a value in the list by subscript
"guangzhou"
127.0.0.1:6379> lindex list 0
"shenzhen"
############################
# llen return length
127.0.0.1:6379> lpush list baiyunqu
(integer) 1
127.0.0.1:6379> lpush list panyuqu
(integer) 2
127.0.0.1:6379> lpush list yuexiuqu
(integer) 3
127.0.0.1:6379> llen list   #Returns the length of the list
(integer) 3
############################
# lrem removes the specified value
# Take off uid
127.0.0.1:6379> lrem list 1 yuexiuqu   #Remove the specified number of value s in the list collection and match them exactly
(integer) 1
127.0.0.1:6379> lrange list 0 -1
1) "tianhequ"
2) "panyuqu"
3) "baiyunqu"
127.0.0.1:6379> lpush list tianhequ
(integer) 4
127.0.0.1:6379> lrem list 2 tianhequ  #Remove the values of 2 tianhqu in the list collection
(integer) 2
127.0.0.1:6379> lrange list 0 -1
1) "panyuqu"
2) "baiyunqu"
############################
# trim. list truncation
127.0.0.1:6379> rpush redislist "zhongshandaxve"
(integer) 1
127.0.0.1:6379> rpush redislist "huananligongdaxve"
(integer) 2
127.0.0.1:6379> rpush redislist "guangdongzhongyiyaodaxve"
(integer) 3
127.0.0.1:6379> rpush redislist "xinghaidaxve"
(integer) 4
127.0.0.1:6379> ltrim redislist 0 1   #The specified length is intercepted by subscript, and the others are deleted
OK
127.0.0.1:6379> lrange redislist 0 -1
1) "zhongshandaxve"
2) "huananligongdaxve"
############################
# rpoplpush   #Removes the last element of the list and moves it to a new list
127.0.0.1:6379> rpush list "beijing"
(integer) 1
127.0.0.1:6379> rpush list "shanghai"
(integer) 2
127.0.0.1:6379> rpush list "guangdong"
(integer) 3
127.0.0.1:6379> rpoplpush list anotherlist   # Move the element guangdong from the list to the new list otherlist
"guangdong"
127.0.0.1:6379> lrange list 0 -1
1) "beijing"
2) "shanghai"
127.0.0.1:6379> lrange anotherlist 0 -1
1) "guangdong"
############################
# lset replaces the value of the specified index in the list with another value to update the operation
127.0.0.1:6379> lpush list "v1"
(integer) 1
127.0.0.1:6379> lrange list 0 0
1) "v1"
127.0.0.1:6379> lset list 0 index   #If it exists, update the value of the current subscript
OK
127.0.0.1:6379> lrange list 0 0
1) "index"
127.0.0.1:6379> lset list 1 item    #If there is no list to update, an error will be reported
(error) ERR index out of range 
############################
# linsert inserts a specific value before or after an element in the list 
127.0.0.1:6379> linsert list world
(error) ERR wrong number of arguments for 'linsert' command
127.0.0.1:6379> rpush list world
(integer) 1
127.0.0.1:6379> rpush list universe
(integer) 2
127.0.0.1:6379> linsert list before "universe" "themilkyway"    #Add an element themilkyway in front of universe
(integer) 3
127.0.0.1:6379> lrange list 0 -1
1) "world"
2) "themilkyway"
3) "universe"
127.0.0.1:6379> linsert list after "universe" "multiverse"    #stay universe Add one later##Element multiverse
(integer) 4
127.0.0.1:6379> lrange list 0 -1
1) "world"
2) "themilkyway"
3) "universe"
4) "multiverse"
List Summary
1)	He is actually a linked list, before Node after,left,right Values can be inserted
2)	If key Does not exist, create a new linked list
3)	If key Existing, new content
4)	If all values are removed, the empty linked list also means that it does not exist
5)	Inserting or changing values on both sides is the most efficient, and the efficiency of intermediate elements is relatively low
 Message queuing( LPUSH rpop),Stack( lpush lpop)

Set

All commands of set start with s
The value in set cannot be repeated

127.0.0.1:6379> sadd set "qinshihuang"   #Add element to set set
(integer) 1
127.0.0.1:6379> sadd set "yandi"
(integer) 1
127.0.0.1:6379> sadd set "wuzetian"
(integer) 1
127.0.0.1:6379> smembers set  #View all values of the specified set
1) "wuzetian"
2) "yandi"
3) "qinshihuang"
127.0.0.1:6379> sismember set tanggaozong   #Determine whether a value is in the set set
(integer) 0  #Returning 0 means No
############################
# scard gets the number of in the collection 
127.0.0.1:6379> scard set   #Gets the number of content elements in the set collection
(integer) 3
############################
# srem removes elements from the collection 
127.0.0.1:6379> srem set zhuyuanzhang  #Removes the specified element from the set collection
(integer) 1
127.0.0.1:6379> scard set
(integer) 3
127.0.0.1:6379> smembers set
1) "wuzetian"
2) "yandi"
3) "qinshihuang"
############################
# Set is an unordered, non repeating set, and random
127.0.0.1:6379> srandmember set   #Select an element at random
"yandi"
127.0.0.1:6379> srandmember set
"wuzetian"
127.0.0.1:6379> srandmember set 2  #Randomly select the specified (2) number of elements
1) "wuzetian"
2) "qinshihuang"
127.0.0.1:6379> srandmember set 2
1) "yandi"
2) "wuzetian"
############################
# spop deletes the specified key and randomly deletes the key
127.0.0.1:6379> spop set   #Randomly delete the elements in the set set
"qinshihuang"
127.0.0.1:6379> smembers set
1) "wuzetian"
############################
# smove moves a specified value to another set set
127.0.0.1:6379> sadd redisset "today"
(integer) 1
127.0.0.1:6379> sadd redisset "tomorrow"
(integer) 1
127.0.0.1:6379> sadd redisset "yesterday"
(integer) 1
127.0.0.1:6379> sadd redisset "day"
(integer) 1
127.0.0.1:6379> smove redisset redisset2 "day"  # Move a specified value in redisset to another redisset2 set
(integer) 1 
127.0.0.1:6379> smembers redisset2
1) "day"
127.0.0.1:6379> smembers redisset
1) "tomorrow"
2) "yesterday"
3) "today"
############################
# smove common concern (microblog, station B)
# Digital set class: difference set: sdiff, intersection: sinter, Union: sunion
127.0.0.1:6379> sadd hey1 ge
(integer) 1
127.0.0.1:6379> sadd hey1 shi
(integer) 1
127.0.0.1:6379> sadd hey1 bai
(integer) 1
127.0.0.1:6379> sadd hey2 bai
(integer) 1
127.0.0.1:6379> sadd hey2 qian
(integer) 1
127.0.0.1:6379> sadd heye ge
(integer) 1
127.0.0.1:6379> sdiff hey1 hey2    #Difference set
1) "ge"
2) "shi"
3) "bai"
127.0.0.1:6379> sinter hey1 hey2   #intersection
1) "bai"
127.0.0.1:6379> sunion hey1 hey2   #Union
1) "qian"
2) "ge"
3) "shi"
4) "bai"

For example, users of Weibo and A put all their followers in one collection and their fans in one collection. Then, they can view their common concerns and hobbies and become second-degree friends (six degree segmentation theory)

Hash (hash)

Map set, key map < key, value > set, this value is the map set. The essence is not much different from the String type, but a simple key value
All hash commands begin with h

127.0.0.1:6379> hset hashnow field1 Monday   #Set a specific key value
(integer) 1
127.0.0.1:6379> hget hashnow field1    #Get a field value
"Monday"
127.0.0.1:6379> hmset hashnow field1 Tuesday field2  Wednesday   #set multiple key values
OK
127.0.0.1:6379> hmget hashnow field1 field2   #Get multiple field values
1) "Tuesday"
2) "Wednesday"
127.0.0.1:6379> hgetall hashnow   #Get all the data
1) "field1"
2) "Tuesday"
3) "field2"
4) "Wednesday"
127.0.0.1:6379> hdel hashnow field1   #Delete the key field specified in hashnow. The corresponding value also disappears
(integer) 1
127.0.0.1:6379> hgetall hashnow
1) "field2"
2) "Wednesday" 
############################
# hlen get length
127.0.0.1:6379> hmset hashnow field1 FromoMonday field2 ToFriday
OK
127.0.0.1:6379> hgetall hashnow
1) "field2"
2) "ToFriday"
3) "field1"
4) "FromoMonday"
127.0.0.1:6379> hlen hashnow   #Gets the number of fields in the hash table
(integer) 2
############################
# hexists determine whether a value exists
127.0.0.1:6379> hexists hashnow field1  #Judge whether the specified field in the hash exists
(integer) 1
127.0.0.1:6379> hexists hashnow field3
(integer) 0
############################
#  hkeys only gets all keys; hvals only gets all value s
127.0.0.1:6379> hkeys hashnow   #Get all field s only
1) "field2"
2) "field1"
127.0.0.1:6379> hvals hashnow   #Only get all value s
1) "ToFriday"
2) "FromoMonday" 
############################
#  hincr  hdecr
127.0.0.1:6379> hset hashnow field3 1000  #Specify an increment of 1000
(integer) 1
127.0.0.1:6379> hincrby hashnow field3 200  #Specify increment
(integer) 1200
127.0.0.1:6379> hincrby hashnow field3 -20
(integer) 1180
127.0.0.1:6379> hsetnx hashnow field4 history  #If it does not exist, it can be set
(integer) 1
127.0.0.1:6379> hsetnx hashnow field4 story   #If it exists, it cannot be set
(integer) 0

# hash can save change data user name age
127.0.0.1:6379> hset user:1 name china
(integer) 1
127.0.0.1:6379> hget user:1 name
"china"
Hash Changed data, especially frequently changing information such as user information, hash More suitable for object storage, String More suitable for string storage
Zset(Ordered set)
stay set Added a value on the basis of, set k1 v1 ;zset k1 score1 v1
 be-all zset All commands are z start
############################
127.0.0.1:6379> zadd setit 1 shuihuzhuan   #Add a value
(integer) 1
127.0.0.1:6379> zadd setit 2 xiyouji 3 hongloumeng  #Add multiple values
(integer) 2
127.0.0.1:6379> zrange setit 0 -1
1) "shuihuzhuan"
2) "xiyouji"
3) "hongloumeng"
############################
#  zrangebyscore sorting
127.0.0.1:6379> zadd salary 4682 chengxvyuan   #Add three users
(integer) 1
127.0.0.1:6379> zadd salary 10800 java
(integer) 1
127.0.0.1:6379> zadd salary 6000 c#
(integer) 1
## zrangebyscore key min max
127.0.0.1:6379> zrangebyscore salary -inf +inf   #Display all users, sorted from small to large (negative infinity - inf, positive infinity + INF)
1) "chengxvyuan"
2) "c#"
3) "java"
127.0.0.1:6379> zrevrange salary 0 -1    #(salary) grades are ranked from large to small
1) "java"
2) "c#" 
127.0.0.1:6379> zrangebyscore salary +inf -inf 
(empty array)
127.0.0.1:6379> zrangebyscore salary -inf +inf withscores  #Show all users with grades (salary)
1) "chengxvyuan"
2) "4682"
3) "c#"
4) "6000"
5) "java"
6) "10800"
127.0.0.1:6379> zrangebyscore salary -inf 6000 withscores  #Displays the ascending order of employees whose salary is less than 6000
1) "chengxvyuan"
2) "4682"
3) "c#"
4) "6000"
############################
#  zrem remove element
127.0.0.1:6379> zrange salary 0 -1
1) "chengxvyuan"
2) "c#"
3) "java"
127.0.0.1:6379> zrem salary chengxvyuan  #Removes the specified element
(integer) 1 
127.0.0.1:6379> zrange salary 0 -1  #View all elements in salary
1) "c#"
2) "java"
127.0.0.1:6379> zcard salary  #Gets the number of in the ordered collection
(integer) 2
############################
#  zcount gets the member variable of the interval
127.0.0.1:6379> zadd myset 1 dog
(integer) 1
127.0.0.1:6379> zadd myset 2 cat 3 insect
(integer) 2
127.0.0.1:6379> zcount myset 0 2  #Gets the member variable [0,2] in the specified collection
(integer) 2

For the rest API s, you can check the official documents at this time if necessary.
Case idea: set sorting, storing class grade table and salary table sorting
Ordinary message, 1. Important message, 2. Judgment with weight
Leaderboard application implementation, taking Top N

Three special data types

Geospatial (geographical location)
Data to be used: http://www.jsons.cn/lngcode/ , the longitude and latitude of the following address positions can be queried by clicking in.
6 commands
1) GEOADD
2) GEODIST
3) GEOHASH
4) GEOPOS
5) GEORADIUS
6) GEORADIUSBYMEMBER
Getadd add geographic location

#Rule: poles (South and North) cannot be added directly. Generally, the city data will be downloaded and imported directly through the java program at one time
#Effective longitude: - 180 to 180; Valid latitude: - 85.05112878 to 85.05112878. An error is returned if the specified range is exceeded
# 127.0.0.1:6379> geoadd china:city 29.66 91.13 lasashi
# (error) ERR invalid longitude,latitude pair 29.660000,91.130000
127.0.0.1:6379> geoadd china:city 91.13 29.66 lasashi
(integer) 1
127.0.0.1:6379> geoadd china:city 126.64 45.75 heilongjiangshi
(integer) 1
127.0.0.1:6379> geoadd china:city 111.67 40.81 huhehaoteshi
(integer) 1 
127.0.0.1:6379> geoadd china:city 114.17 22.26 hongkong
(integer) 1
127.0.0.1:6379> geoadd china:city 113.54 22.19 aomen 121.56 25.03 taiwan
(integer) 2
GEODIST 
# Distance unit before both
# M: Unit: meter; km: expressed in kilometers; mi: unit: mile; ft: expressed in feet
127.0.0.1:6379> geodist china:city hongkong heilongjiangshi  #View the straight-line distance from Hong Kong to Heilongjiang city. The default is m
"2846471.3986"
127.0.0.1:6379> geodist china:city hongkong heilongjiangshi km 
"2846.4714"

GEOHASH returns one or more location elements

127.0.0.1:6379> geohash china:city aomen taiwan  #Convert two-dimensional latitude and longitude into one-dimensional string. The closer the two strings are, the closer the distance is
1) "webwpxt61g0"
2) "wsqqqht6360"

GEOPOS gets the longitude and latitude of the specified city (which is a coordinate value)

127.0.0.1:6379> geopos china:city lasashi
1) 1) "91.1300012469291687"
   2) "29.66000035782676747"
127.0.0.1:6379> geopos china:city lasashi aomen
1) 1) "91.1300012469291687"
   2) "29.66000035782676747"
2) 1) "113.54000240564346313"
   2) "22.18999967077372304"

GEORADIUS takes the given latitude and longitude as the center to find out the elements within a certain radius

#See people nearby? (get the address and location of all nearby people) query through the radius
127.0.0.1:6379> georadius china:city 100 30 1000 km  # Obtain the current longitude and latitude (100, 30). Take this longitude and latitude as the center, and query the city within 1000km. The premise is that all data are entered into china:city
1) "lasashi"
127.0.0.1:6379> georadius china:city 100 30 5000 km
1) "lasashi"
2) "aomen"
3) "hongkong"
4) "taiwan"
5) "heilongjiangshi"
127.0.0.1:6379> georadius china:city 100 30 5000 km withdist   #Displays the position of xx to the center distance
1) 1) "lasashi"
   2) "856.4817"
2) 1) "aomen"
   2) "1605.3969"
3) 1) "hongkong"
   2) "1654.1187"
4) 1) "taiwan"
   2) "2193.6677"
5) 1) "heilongjiangshi"
   2) "2899.0121"
127.0.0.1:6379> georadius china:city 100 30 5000 km withcoord  #Display latitude and longitude
1) 1) "lasashi"
   2) 1) "91.1300012469291687"
      2) "29.66000035782676747"
2) 1) "aomen"
   2) 1) "113.54000240564346313"
      2) "22.18999967077372304"
3) 1) "hongkong"
   2) 1) "114.16999965906143188"
      2) "22.26000106503118303"
4) 1) "taiwan"
   2) 1) "121.56000047922134399"
      2) "25.03000011182229656"
5) 1) "heilongjiangshi"
   2) 1) "126.64000242948532104"
      2) "45.74999965248261447"
#Get a specified number of people
127.0.0.1:6379> georadius china:city 100 30 5000 km withdist withcoord count 3  #Filter out the specified results
1) 1) "lasashi"
   2) "856.4817"
   3) 1) "91.1300012469291687"
      2) "29.66000035782676747"
2) 1) "aomen"
   2) "1605.3969"
   3) 1) "113.54000240564346313"
      2) "22.18999967077372304"
3) 1) "hongkong"
   2) "1654.1187"
   3) 1) "114.16999965906143188"
      2) "22.26000106503118303"

GEORADIUSBYMEMBER finds other elements around the specified element

127.0.0.1:6379> georadiusbymember china:city hongkong 3000 km
1) "lasashi"
2) "aomen"
3) "hongkong"
4) "taiwan"
5) "heilongjiangshi"
127.0.0.1:6379> georadiusbymember china:city hongkong 300 km
1) "aomen"
2) "hongkong"
#Principle: the underlying implementation principle is actually Zset. You can use the Zset command to operate geo
127.0.0.1:6379> zrange china:city 0 -1  #View all elements in the map
1) "lasashi"
2) "aomen"
3) "hongkong"
4) "taiwan"
5) "heilongjiangshi"
127.0.0.1:6379> zrem china:city heilongjiangshi  #Removes the specified element
(integer) 1
127.0.0.1:6379> zrange china:city 0 -1
1) "lasashi"
2) "aomen"
3) "hongkong

Hyperloglog
Advantages: the occupied memory is four fixed, and the technology of 2 ^ 64 different elements only needs 12kb memory. If you want to compare it from the perspective of memory, hyperloglog is preferred
The hyperloglog data structure is updated in redis 2.89
Redis hyperloglog cardinality statistics algorithm
UV of web page (a person visits a website many times, but still counts as a person)
In the traditional way, set saves the user id, and then the number of elements in set can be counted as the standard judgment
If you save a large number of user IDs in this way, it will be more troublesome. Our purpose is to count, not save user IDs

127.0.0.1:6379> pfadd pfset a s d f g h j k l  #Create the first set of elements
(integer) 1
127.0.0.1:6379> pfcount pfset  #Count the number of cardinality (non repetition) of the first group of elements
(integer) 9
127.0.0.1:6379> pfadd pfset1 q w e r t y u i o  #Create a second set of elements 
(integer) 1
127.0.0.1:6379> pfcount pfset1
(integer) 9
127.0.0.1:6379> pfmerge pfset2 pfset pfset1  #Merge two sets of elements into a new element (pfset2)
OK 
127.0.0.1:6379> pfcount pfset2  #View the number of union sets
(integer) 17  

If fault tolerance is allowed, you can use hyperloglog; If not allowed, use set or its own data type
Bitmaps (bitmaps, data structures. They are recorded by binary operation, and there are only two states: 0 and 1)
Bit storage (represented by 0 and 1)
Statistics user information, active, inactive. You can use bitmaps in both login and not login states

For example: the clock in time of a week, the index starts from 0, and 0 represents Monday
127.0.0.1:6379> setbit sign 0 1   #Check in 0 represents Monday and 1 represents clocked in
(integer) 0
127.0.0.1:6379> setbit sign 1 1
(integer) 0
127.0.0.1:6379> setbit sign 2 1
(integer) 0
127.0.0.1:6379> setbit sign 3 1
(integer) 0
127.0.0.1:6379> setbit sign 4 0  #Sign in 4 means Friday, and 0 means no clock in
(integer) 0
127.0.0.1:6379> setbit sign 5 1
(integer) 0
127.0.0.1:6379> setbit sign 6 1
(integer) 0
#Check whether to clock in a day
127.0.0.1:6379> getbit sign 4  #Check whether you clock in on Friday
(integer) 0  #Returning 0 means no clock in
127.0.0.1:6379> getbit sign 5
(integer) 1
#Count clock in days
127.0.0.1:6379> bitcount sign  #Check the clock in days of this week to check whether you are full attendance
(integer) 6

Keywords: Redis

Added by xardas on Mon, 22 Nov 2021 01:42:26 +0200