current position:Home>About redis, all the operations you need are here~

About redis, all the operations you need are here~

2022-01-26 23:00:42 Classmate an downstairs

NoSQL summary

development history

1、 stand-alone MySQL The s

 Insert picture description here

​ At the beginning of website development , The number of visits to the website is basically not too large , A single database is enough , At that time, it was basically static web pages HTML There is no pressure on the server .

​ If the amount of data is too large , A machine won't fit ,B+Tree( The index can't fit anymore ), Too many visits , A server can't stand it , As long as the above three situations occur , Must be promoted .

2、Memcached( cache )+ MySQl+ Split Vertically ( Read / write separation )

Website 80% The situation is reading , It's very troublesome every time you query , So use cache to ensure efficiency !

Development process : Optimize data structures and indexes --> Query index (IO) --> Memcached

 Insert picture description here

3、 Sub database and sub table + Horizontal split + MySQl colony

In the process of Technological Development , The demands on people have increased , Former mysql Replaced with MySQL colony .

The essence : database ( Reading and writing )

MyISAM --> Table locks

Innodb --> Row lock

Now? : Sub database and sub table Solve the pressure of writing

4、 Today's era

2010 ---- 2020, Technology explosion ,mysql The relational database is not enough , Large amount of data , Fast change !

Use a dedicated database to process files , picture , Blog , And so on , Reduce MySQL The pressure of the .

5、 At present, the basic website model

 Insert picture description here

Why use NoSQL

​ User's personal information , Social networks , Location, etc , Data explosion growth .

​ At this time we will use NoSQL Database ,NoSQL Can handle the above situation well !

What is? NoSQL

NoSQL = Not Only SQL ( not only SQL) Non relational database in general

Relational database : form , That's ok , Column

NoSQl In today's big data environment, it is developing very rapidly ,Redis It's the fastest growing , We have to master !

A lot of data types, user's personal information , Social networks , Location , The advantages of these data types do not require a fixed format , It can be extended horizontally without redundant operations !

1、NoSQl characteristic

decoupling !!!

  • Easy to expand ( There's no relationship between the data , Good extension )

  • Large amount of data , High performance (Redis Write in a second 8W Time , Read 11 ten thousand )

  • Data types are diverse !( There's no need to design the database in advance ! Take it and use it )

  • Conventional RDBMS( Structured organization 、SQL、 There are separate tables for both data and relationships 、 Uniformity 、 Basic business ) and NoSQL( There is no fixed query language 、 It's not just data 、 Key value pair 、 Final consistency 、CAP Theorem and BASE、 Three tenors )

2、 understand :3V + 3 high ( big data )

In the era of big data 3V: Massive (Volume)、 diverse (Variety)、 real time (Velocity)

In the era of big data 3V: High concurrency 、 High availability 、 Highly expandable

NoSQl Four categories

  1. k-v Key value pair (Redis、Oracle BDB)

sina:Redis

Meituan :Redis + Tair

Ali 、du:Redis + memecache

  1. Document database (MongoDB、ConthDB)
  2. Column store database (HBase、 distributed file system )
  3. Graph relational database (Neo4J、InfoGrid It's about relationships

Redis What is it? ?

Redis(Remote Dictionary Server ), namely Remote Dictionary Service , It's a Open source Use ANSIC Language writing 、 Support network 、 Log type that can be memory based or persistent 、Key-Value database , And provide multilingual API, free 、 Open source .

Redis Can do ?

1、 Memory based , Can be persistent

2、 For caching ( The home page information of the website )

3、 Do message queuing

4、 Make a counter ( give the thumbs-up 、 Comment on 、 Collection )

5、 Other

Redis install

windows

1. download

github Address : https://github.com/tporadowski/redis/releases

  1. After downloading, unzip it to the environment directory
  2. Turn on Redis, Double click Run service (redis-server.exe) The default port is :6379
  3. Use the client connection service (redis-cli.exe) Input ping appear PONG The connection is successful !

Linux

  1. download linux Installation package redis-5.0.8.tar.gz
  2. decompression Redis Installation package , Program /opt
  3. Enter the extracted file , Can see redis Configuration file for
  4. Basic environment installation
yum install gcc-c++

make
make install 
  1. redis Default installation path user/local/bin/

6. take redis The configuration file , Copy to current directory

7. start-up redis service ( function redis-server ……) Test connection redis -cli -p 6379 -->ping -->PONG

Test performance

  1. Installed Redis Open in directory redis-benchmark.exe file , Automatically complete the test
  2. test result

 Insert picture description here

request 10 Ten thousand pieces of data used 2.79s,50 Client requests ,3 A payload of bytes , A session is maintained !

so Redis The speed is very, very fast !

Basic knowledge of

Redis The default is 16 A database , By default The first 0 individual database

  1. Switch database select 1 Enter the first database –
  2. View all of the database keykey *
  3. Clear the current database flushdb
  4. Clear all databases FLUSHALL

reflection : Why? redis Use 6379 As port ?

– The name of a female star squared paper for practicing calligraphy

5.Redis It's single threaded !

​ Redis It's based on memory operations ,CPU No Redis Performance bottleneck ,Redis The bottleneck is based on the memory and network bandwidth of the machine , Since you use one-way to use , Just use a single thread , So use a single thread !

​ Redis yes C Written language , The official data is 100000 + Of QPS, No more than use kv Of Memecache Bad !

6、redis Why is single thread so fast ?

1、 Mistake 1 : High performance servers must be multithreaded

2、 Mistake 2 : Multithreading must be more efficient than multithreading

The core :Redis Is to put all the data in memory , So using single thread to operate is the highest efficiency , Multithreading (CPU Context switch : Time consuming ), For memory systems , If there is no context, the switching efficiency is the highest ! Read and write many times in the same CPU Upper , In the case of memory , This is the best solution !

Redis Five data types

Official documents :http://www.redis.cn/commands.html

Redis-Key

FlUSHDB #  Clear current database 
FLUSHALL	#  Clear all database data 
keys *	#  View all key value 
set name mhan #  Set the key (name) The value of is (mhan)
EXISTS name #  View key  name  Whether there is 
move name 1 #  Remove key  1 For the current database 
get name #  obtain name Value 
EXPIRE name 10 #  Set up name  The expiration time of , The unit is seconds  ( Single sign on )
ttl name #  see key(name) How long does it take to expire 
type name #  see key A type of 

1、String( character string )

-------------------------------------------------------------------------------
127.0.0.1:6379> set key1 hello,  #  Set up key  The value is hello
OK
127.0.0.1:6379> APPEND key1 world! #  Append string   If key non-existent , The new key
(integer) 12
127.0.0.1:6379> STRLEN key1 #  Gets the length of the string 
(integer) 12
127.0.0.1:6379> get key1 #  obtain key
"hello,world!"
127.0.0.1:6379> EXISTS key1 #  see key Whether there is 
(integer) 1
-------------------------------------------------------------------------------
127.0.0.1:6379> set views 0 #  Set up views( Browse volume , zero )
OK
127.0.0.1:6379> incr views #  Set up views Self increasing 1
(integer) 1
127.0.0.1:6379> incr views
(integer) 2
127.0.0.1:6379> decr views #  Set up views Self reduction 1
(integer) 1
127.0.0.1:6379> INCRBY views 10 #  Set up views Self increasing   In steps of 10
(integer) 11
127.0.0.1:6379> DECRBY views 10 #  Set up views Self reduction   In steps of 10
(integer) 1
-------------------------------------------------------------------------------
#  Intercept string range 
127.0.0.1:6379> set key1 archpan
OK
127.0.0.1:6379> GETRANGE key1 0 3 #  String interception  [0,3]
"arch"
127.0.0.1:6379> GETRANGE key1 0 -1 #  Take all strings  [0,-1]
"archpan"
-------------------------------------------------------------------------------
#  Replace 
127.0.0.1:6379> set key2 abcdefg
OK
127.0.0.1:6379> SETRANGE key2 1 xx  #  Replace the string starting at the specified position 
(integer) 7
127.0.0.1:6379> get key2
"axxdefg"
-------------------------------------------------------------------------------
# setex (set with expire) #  Set expiration time 
# setnx (set if not exist) #  There is no reset ( Commonly used for distributed locks )

127.0.0.1:6379> setex key3 30 "hello" #  Set up  key3  The expiration date is 30 second 
OK
127.0.0.1:6379> ttl key3 #  View remaining effective time 
(integer) 22
127.0.0.1:6379> setnx mykey "mongoDB" #  If mykey Set when not present 
(integer) 1
127.0.0.1:6379> get mykey
"mongoDB"
127.0.0.1:6379> setnx mykey "mongoDB1" #  If mykey In existence , Create failure 
(integer) 0
127.0.0.1:6379> get mykey
"mongoDB"
-------------------------------------------------------------------------------
# mset  Set multiple values at the same time 
# mget  Get multiple values at the same time 
127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3 #  Set up k1,k2,k3
OK
127.0.0.1:6379> mget k1 k2 k3 #  obtain k1,k2,k3
1) "v1"
2) "v2"
3) "v3"
127.0.0.1:6379> msetnx k1 v1 k4 v4 #  If it doesn't exist, set 
(integer) 0
127.0.0.1:6379> keys * #  Failed to set the previous step , because redis It's atomic ( All or nothing --)
1) "k3"
2) "k2"
3) "k1"
-------------------------------------------------------------------------------
#  object 
set user:{name:zhangsan,age:13} #  Set up a user:1 object   The value is json Characters to save 

#  there key It's a clever design : user:{id}:{fields} , stay redis Chinese is completely ok Of !

127.0.0.1:6379> mset user:1:name zhangsan user:1:age 13
OK
127.0.0.1:6379> mget user:1:name user:1:age
1) "zhangsan"
2) "13"
-------------------------------------------------------------------------------
# getset  First get after set
127.0.0.1:6379> getset db redis #  Returns if it does not exist nil
(nil)
127.0.0.1:6379> get db
"redis"
127.0.0.1:6379> getset db mongodb #  If there is , Get the original value , And set new values 
"redis"
127.0.0.1:6379> get db
"mongodb"
-------------------------------------------------------------------------------

String Similar usage scenarios :value In addition to strings, it can also be numbers !

  • Counter
  • Count the number of multiple units
  • Number of fans
  • Object cache storage !

2、List( list )

Using the list, you can do some operations ( queue 、 Stack 、 Blocking queues )

be-all list Order to clean up L At the beginning , Case insensitive

-------------------------------------------------------------------------------
127.0.0.1:6379> LPUSH list one  #  Insert one or more values into the list header 
(integer) 1
127.0.0.1:6379> LPUSH list two
(integer) 2
127.0.0.1:6379> LPUSH list three
(integer) 3
127.0.0.1:6379> LRANGE list 0 -1 #  obtain list The value in (0 - -1 For all )
1) "three"
2) "two"
3) "one"
127.0.0.1:6379> LRANGE list 0 1 #  Get specific values through intervals 
1) "three"
2) "two"
127.0.0.1:6379> RPUSH list mhan #  Insert one or more values at the end of the list 
(integer) 4 
-------------------------------------------------------------------------------
LPOP #  remove list The first element of 
RPOP #  remove list Last element of 

127.0.0.1:6379> LPOP list #  remove list The first element of 
"three" 
127.0.0.1:6379> RPOP list #  remove list Last element of 
"mhan"
127.0.0.1:6379> LRANGE list 0 -1 #  obtain list All the values in 
1) "two"
2) "one"
-------------------------------------------------------------------------------
Lindex #  Get the specific value by subscript 

127.0.0.1:6379> LRANGE list 0 -1
1) "two"
2) "one"
127.0.0.1:6379> LINDEX list 1  #  Get the specific value by subscript 
"one"
-------------------------------------------------------------------------------
Llen #  Get the length of the list 

127.0.0.1:6379> LLEN list			
(integer) 2
-------------------------------------------------------------------------------
#  Remove the specified value  LREM

127.0.0.1:6379> LREM list 1 hello #  Remove the value specified in the list , Remove a , accurate 
(integer) 1
-------------------------------------------------------------------------------
# LTRIM  Intercept 

127.0.0.1:6379> LRANGE list 0 -1
1) "hello"
2) "two"
3) "one"
127.0.0.1:6379> Ltrim list 1 2 #  Intercept the specified length by subscript ,list Be changed .
OK
127.0.0.1:6379> LRANGE list 0 -1
1) "two"
2) "one"
-------------------------------------------------------------------------------
rpoplpush #  Remove the last element of the list and add it to the target list 

127.0.0.1:6379> rpush mylist "hello"
(integer) 1
127.0.0.1:6379> rpush mylist "hello1"
(integer) 2
127.0.0.1:6379> RPOPLPUSH mylist mylist2 #  Remove the last element in the list , Add a new list 
"hello1"
127.0.0.1:6379> LRANGE mylist 0 -1 #  View the original list 
1) "hello"
127.0.0.1:6379> LRANGE mylist2 0 -1 #  The new list does exist 
1) "hello1"
-------------------------------------------------------------------------------
# lset  Replace the value of the specified subscript in the list with another value , update operation 

127.0.0.1:6379> EXISTS list   #  Determine if the list exists 
(integer) 0
127.0.0.1:6379> lset list 0 item  #  If there is no list, we will report an error when we update it 
(error) ERR no such key
127.0.0.1:6379> lpush list value1  
(integer) 1
127.0.0.1:6379> LRANGE list 0 0 
1) "value1"
127.0.0.1:6379> lset list 0 item  #  If there is , Update the value of the current subscript 
OK
127.0.0.1:6379> LRANGE list 0 0 
1) "item"
127.0.0.1:6379> lset list 1 other  #  If it doesn't exist , May be an error !
(error) ERR index out of range
-------------------------------------------------------------------------------
# linsert  Put a specific value Insert before or after an element in the column 

127.0.0.1:6379> RPUSH mylist "hello"    #  Note that this is not Lpush  It is Rpush  Pay attention to the order 
(integer) 1
127.0.0.1:6379> RPUSH mylist "world"
(integer) 2
127.0.0.1:6379> LINSERT mylist before "world" "other"
(integer) 3
127.0.0.1:6379> LRANGE mylist 0 -1
1) "hello"
2) "other"
3) "world"
127.0.0.1:6379> LINSERT mylist after "world" new
(integer) 4
127.0.0.1:6379> LRANGE mylist 0 -1
1) "hello"
2) "other"
3) "world"
4) "new"

Summary :

1、 A list is actually a linked list ,before Node after,left ,right You can insert values

2、 If key non-existent , Create a new list

3、 If key There is , The new content

4、 If the viewed value is removed , Empty list , It also means that there is no such thing as !

5、 Insert or change values on both sides , Highest efficiency ! If the linked list is very long , The middle element , Relatively speaking, the efficiency will be a little lower

Message queuing ! Message queue (LPush Rpop) Enter from the left , Take it out on the right Stack (Lpush Lpop) Enter from the left On the left

3、 aggregate (Set)

be-all Set It's all about S At the beginning

# Smembers  View specified set All values 
# SisMember  Determine whether a value is in set Collection , Be similar to Java:contains
127.0.0.1:6379> sadd myset "hello"    # set Add elements to the collection   Be careful set The value in cannot be repeated !
(integer) 1
127.0.0.1:6379> sadd myset ""   
(integer) 1
127.0.0.1:6379> sadd myset "ichpan"
(integer) 1
127.0.0.1:6379> SMEMBERS myset  #  View specified set All values 
1) "ichpan"
2) "hello"
3) "" 
127.0.0.1:6379> SISMEMBER myset hello  #  Determine whether a value is in set Collection !
(integer) 1
127.0.0.1:6379> SISMEMBER myset world
(integer) 0
-------------------------------------------------------------------------------
# Scard  obtain set The number of content elements in the collection 
127.0.0.1:6379> SCARD myset  #  obtain set The number of content elements in the collection !
(integer) 4
-------------------------------------------------------------------------------
# Srem  remove set The specified element in the collection 
127.0.0.1:6379> srem myset hello  #  remove set The specified element in the collection 
(integer) 1
127.0.0.1:6379> SCARD myset
(integer) 3
127.0.0.1:6379> smembers myset
1) "ichpan"
2) ""
3) "ichpan1"
-------------------------------------------------------------------------------
# SRandMember  Randomly select a specified number of elements 

set It's an unordered, non repeating set , Can be used to draw random .

127.0.0.1:6379> SMEMBERS myset
1) "ichpan"
2) ""
3) "ichpan1"
127.0.0.1:6379> SRANDMEMBER myset  #  Randomly select an element 
""
127.0.0.1:6379> SRANDMEMBER myset
"ichpan"
127.0.0.1:6379> SRANDMEMBER myset 2  #  Randomly select a specified number of elements 
1) "ichpan"
2) "ichpan1"
-------------------------------------------------------------------------------
# Spop  Random delete key
127.0.0.1:6379> SMEMBERS myset
1) "ichpan"
2) ""
3) "ichpan1"
127.0.0.1:6379> spop myset  #  Random delete key  attach : Stack pop-up function pop()
"ichpan"
127.0.0.1:6379> spop myset 
"ichpan1"
127.0.0.1:6379> SMEMBERS myset
1) ""
-------------------------------------------------------------------------------
# SMove  Set a specified value , Move to another set aggregate 
127.0.0.1:6379> sadd myset "hello"
(integer) 1
127.0.0.1:6379> sadd myset "world"
(integer) 1
127.0.0.1:6379> sadd myset ""
(integer) 1
127.0.0.1:6379> sadd myset2 set2
(integer) 1
127.0.0.1:6379> smove myset myset2   #  Set a specified value , Move to another set aggregate !
(integer) 1
127.0.0.1:6379> SMEMBERS myset
1) "hello"
2) "world"
127.0.0.1:6379> SMEMBERS myset2
1) ""
2) "set2"
-------------------------------------------------------------------------------
 Microblogging ,B standing , Pay close attention to !( Combine )
	 Here we can put key1 As a up Lord 1,a/b/c yes up Lord 1 A fan of 
		    hold key2 As a up Lord 2,c/d/e yes up Lord 2 A fan of 
 Mathematical set class :
	-  Difference set 
	-  intersection 
	-  Combine 
127.0.0.1:6379> sadd key1 a
(integer) 1
127.0.0.1:6379> sadd key1 b
(integer) 1
127.0.0.1:6379> sadd key1 c
(integer) 1
127.0.0.1:6379> sadd key2 c
(integer) 1
127.0.0.1:6379> sadd key2 d
(integer) 1
127.0.0.1:6379> sadd key2 e
(integer) 1
# sdiff
127.0.0.1:6379> sdiff key1 key2    #  Difference set   Pay attention to key1 For reference 
1) "b"
2) "a"
# sinter
127.0.0.1:6379> sinter key1 key2    #  intersection   Common friends can do this 
1) "c" 
# sunion
127.0.0.1:6379> sunion key1 key2   #  Combine  
1) "b"
2) "c"
3) "e"
4) "a"
5) "d"

 Microblogging ,A Users put all the people they care about in one set Collection ! Put its fans in a collection, too !
 Pay close attention to , A common hobby , Two degree friends , Recommend friends !( Six degree segmentation theory )

4、Hash( Hash )

You can understand map aggregate key-value form , Just this value It's a map The form of a collection , The nature and String There's no big difference in type , It's still a simple key-vlaue!

-------------------------------------------------------------------------------
# hset
127.0.0.1:6379> hset myhash field1   # set  A specific  key-value
(integer) 1
# hget
127.0.0.1:6379> hget myhash field1  #  obtain 1 Field values 
""
# hmset
127.0.0.1:6379> hmset myhash field1 hello field2 world  # set  Multiple specific  key-value  Existence covers 
OK
# hkeys
127.0.0.1:6379> hkeys myhash  #  Just get all key
1) "field2"
2) "field1"
# hvals
127.0.0.1:6379> hvals myhash  #  Just get all value
1) "world"
2) "hello"
# hmget
127.0.0.1:6379> hmget myhash field1 field2   #  Get multiple field values 
1) "hello"
2) "world"
# hgetall
127.0.0.1:6379> hgetall myhash  #  Get all the data in the hash 
1) "field1"
2) "hello"
3) "field2"
4) "world"
# hlen
127.0.0.1:6379> hlen myhash  #  Get the number of hash table fields 
(integer) 2
# hdel
127.0.0.1:6379>  hdel myhash field1  #  Delete hash Appoint key Field : Corresponding value The value disappears 
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "field2"
2) "world"
# hexists
127.0.0.1:6379> hexists myhash field2  #  Judge hash Specifies whether the field exists !
(integer) 1
127.0.0.1:6379> hexists myhash field3
(integer) 0
-------------------------------------------------------------------------------
127.0.0.1:6379> hset myhash field3 5
(integer) 1
# incr
127.0.0.1:6379> hincrby myhash field3 1  #  Set the gain 1
(integer) 6
#  reverse incr = decr
127.0.0.1:6379> hincrby myhash field3 -1  #  Set self subtraction 
(integer) 5
# hsetnx
127.0.0.1:6379> hsetnx myhash field4 hello  #  If it does not exist, it can be set 
(integer) 1
127.0.0.1:6379> hsetnx myhash field4 world  #  If it exists, it cannot be set 
(integer) 0
-------------------------------------------------------------------------------
# hset
127.0.0.1:6379> hset myhash field1   # set  A specific  key-value
(integer) 1
# hget
127.0.0.1:6379> hget myhash field1  #  obtain 1 Field values 
""
# hmset
127.0.0.1:6379> hmset myhash field1 hello field2 world  # set  Multiple specific  key-value  Existence covers 
OK
# hkeys
127.0.0.1:6379> hkeys myhash  #  Just get all key
1) "field2"
2) "field1"
# hvals
127.0.0.1:6379> hvals myhash  #  Just get all value
1) "world"
2) "hello"
# hmget
127.0.0.1:6379> hmget myhash field1 field2   #  Get multiple field values 
1) "hello"
2) "world"
# hgetall
127.0.0.1:6379> hgetall myhash  #  Get all the data in the hash 
1) "field1"
2) "hello"
3) "field2"
4) "world"
# hlen
127.0.0.1:6379> hlen myhash  #  Get the number of hash table fields 
(integer) 2
# hdel
127.0.0.1:6379>  hdel myhash field1  #  Delete hash Appoint key Field : Corresponding value The value disappears 
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "field2"
2) "world"
# hexists
127.0.0.1:6379> hexists myhash field2  #  Judge hash Specifies whether the field exists !
(integer) 1
127.0.0.1:6379> hexists myhash field3
(integer) 0
-------------------------------------------------------------------------------
127.0.0.1:6379> hset myhash field3 5
(integer) 1
# incr
127.0.0.1:6379> hincrby myhash field3 1  #  Set the gain 1
(integer) 6
#  reverse incr = decr
127.0.0.1:6379> hincrby myhash field3 -1  #  Set self subtraction 
(integer) 5
# hsetnx
127.0.0.1:6379> hsetnx myhash field4 hello  #  If it does not exist, it can be set 
(integer) 1
127.0.0.1:6379> hsetnx myhash field4 world  #  If it exists, it cannot be set 
(integer) 0
-------------------------------------------------------------------------------

hash Change data ,user name age , It is especially used for saving user information , Constantly changing information !
hash More suitable for object The storage ,String More suitable character string Storage

5、Zset( Ordered set )

Zset and Set One more. Z, stay set A value is added to that of ,set k1 v1 ,zset k1 score1 v1

-------------------------------------------------------------------------------
# Zadd
127.0.0.1:6379> zadd myset 1 one #  add to 1 It's worth 
(integer) 1
127.0.0.1:6379> zadd myset 2 two 3 three  #  Add multiple values 
(integer) 2
# Zrange
127.0.0.1:6379> zrange myset 0 -1 #  Traverse print all data 
1) "one"
2) "two"
-------------------------------------------------------------------------------
127.0.0.1:6379> zadd salary 2500 zhangsan #  add to 3 Users 
(integer) 1
127.0.0.1:6379> zadd salary 5000 xiaoming
(integer) 1
127.0.0.1:6379> zadd salary 500 
(integer) 1
# ZrangeByScore
127.0.0.1:6379> ZRANGEBYSCORE salary -inf +inf  #  Show all users [ From small to large ]
1) ""
2) "zhangsan"
3) "xiaoming"
# ZrevRange
127.0.0.1:6379> ZREVRANGE salary 0 -1  # [ From big to small ]  Sort  rev The meaning of reversal 
1) "xiaoming" 
2) "zhangsan"
3) ""
127.0.0.1:6379> ZRANGEBYSCORE salary -inf 2500 withscores #  Show salary less than 2500 In ascending order 
1) ""
2) "500"
3) "zhangsan"
4) "2500"
# zrem
127.0.0.1:6379> zrem salary xiaoming  #  Remove elements from an ordered collection 
(integer) 1
127.0.0.1:6379> zrange salary 0 -1
1) ""
2) "zhangsan"
# zcard 
127.0.0.1:6379> zcard salary  #  Get the number of ordered sets 
(integer) 2
-------------------------------------------------------------------------------
127.0.0.1:6379> zadd myset 1 hello
(integer) 1
127.0.0.1:6379> zadd myset 2 world 3 
(integer) 2
# zcount
127.0.0.1:6379> zcount myset 1 3  #  Get the number of members in the specified interval 
(integer) 3
127.0.0.1:6379> zcount myset 1 2
(integer) 2
-------------------------------------------------------------------------------

Case thinking :set Sort and store the class grade table , Payroll sort !
General news ,1. Important news 2. Judge with weight !
bilibili Hot leaderboard application implementation (set Collection sorting Refresh by minute )

Three special data types

1、geospatial Geographical location and space

Friends' positioning , The man near the , Taxi distance calculation ?
Redis Of Geo stay Redis3.2 The version was launched ! This function can calculate the location information , The distance between the two places , People in a few miles around !
You can query some test data :https://jingweidu.51240.com/

Only 6 An order

  • geoadd( Add location )
# getadd  Add location 
#  The rules : The north and South levels cannot be added directly , We usually download city data , Directly through java The program is imported once !
#  Parameters  key  value ( latitude 、 longitude 、 name )
#  Effective longitude from -180 C to 180 degree .
#  Effective latitude from -85.05112878 C to 85.05112878 degree .
#  When the coordinate position exceeds the specified range above , This command will return an error 
# (error) ERR invalid longitude,latitude pair 39.900000,116.400000
127.0.0.1:6379> geoadd china:city 116.40 39.90 beijing
(integer) 1
127.0.0.1:6379> geoadd china:city 121.47 31.23 shanghai 106.50 29.53 chongqing
(integer) 2
127.0.0.1:6379> geoadd china:city 120.16 30.24 hangzhou 108.96 34.26 xian 114.05 22.52 shenzhen
(integer) 3
  • geopos( Or the current location : It must be a coordinate value !)
127.0.0.1:6379> geopos china:city hangzhou beijing  #  Get the longitude and latitude of the specified city 
1) 1) "120.1600000262260437"
   2) "30.2400003229490224"
2) 1) "116.39999896287918091"
   2) "39.90000009167092543"
  • geodist ( Returns the distance between two given positions )
  • m Expressed in meters .
  • km Expressed in kilometers .
  • mi In miles .
  • ft In feet .

If the user does not explicitly specify the unit parameter , that GEODIST The default is meters .

127.0.0.1:6379> geodist china:city hangzhou shanghai #  Check the straight-line distance from Hangzhou to Shanghai   Company : rice 
"166761.2770"
127.0.0.1:6379> geodist china:city hangzhou beijing km  #  Check the straight-line distance from Hangzhou to Beijing   Company : km 
"1127.3378"
  • georadius ( Centered on a given latitude and longitude , Find the elements in a certain radius )

How to achieve : People around me ?( Get the addresses of all nearby people , location !) Query by radius !

127.0.0.1:6379> GEORADIUS china:city 110 30 1000 km   #  With 110,30 This longitude and latitude are the center , Looking for a square circle 1000km The city inside   Premise : All data should be entered :china:city, Will make the results more accurate ! 
1) "chongqing"
2) "xian"
3) "shenzhen"
4) "hangzhou"
127.0.0.1:6379> GEORADIUS china:city 110 30 500 km withdist #  Displays the straight-line distance to the middle position   radius 500km
1) 1) "chongqing"
   2) "341.9374"
2) 1) "xian"
   2) "483.8340"
127.0.0.1:6379> GEORADIUS china:city 110 30 500 km withcoord #  Displays the radius of the distance to the center 500km In the city  +  Latitude and longitude information 
1) 1) "chongqing"
   2) 1) "106.49999767541885376"
      2) "29.52999957900659211"
2) 1) "xian"
   2) 1) "108.96000176668167114"
      2) "34.25999964418929977"
127.0.0.1:6379> GEORADIUS china:city 110 30 500 km withcoord withdist count 3 #  Filter out the specified results   Display only 2 One is because only 2 individual 
1) 1) "chongqing"
   2) "341.9374"
   3) 1) "106.49999767541885376"
      2) "29.52999957900659211"
2) 1) "xian"
   2) "483.8340"
   3) 1) "108.96000176668167114"
      2) "34.25999964418929977"
  • GEORADIUSBYMEMBER
#  Find the elements in the specified range , The center point is determined by a given location element 
127.0.0.1:6379> GEORADIUSBYMEMBER china:city beijing 1000 km
1) "beijing"
2) "xian"
127.0.0.1:6379> GEORADIUSBYMEMBER china:city shanghai 500 km
1) "hangzhou"
2) "shanghai"
  • GEOHASH command ( Returns the... Of one or more positional elements Geohash Express )

The command will return 11 A character Geohash character string

#  Convert two-dimensional latitude and longitude into one-dimensional string , If the two strings are closer , So the closer we get !
127.0.0.1:6379> GEOHASH china:city beijing chongqing
1) "wx4fbxxfke0"
2) "wm5xzrybty0"
  • GEO The underlying implementation principle :Zset! We can use Zset Command to operate Geo
127.0.0.1:6379> zrem china:city beijing  #  Removes the specified element 
(integer) 1
127.0.0.1:6379> ZRANGE china:city 0 -1  #  View all elements in the map 
1) "chongqing"
2) "xian"
3) "shenzhen"
4) "hangzhou"
5) "shanghai"

2、hyperloglog Bitmap

What is the cardinality ?( Non repeating elements in a collection )

  • brief introduction

Redis 2.8.9 The version is updated Hyperloglog data structure !

Redis Hyperloglog The algorithm of cardinality Statistics !

** advantage :** The memory occupied is fixed ,2^64 Different elements of Technology , Just waste 12kb Memory . If you want to compare from the memory point of view Hyperloglog The preferred !

Web page UV( A person visits a website many times , But still count as a person !)

The traditional way ,set Save the user's id, And then you can count set The number of elements in as a standard judgment !

This way, if you save a large number of users id, It will be more troublesome ! Our purpose is to count , Instead of saving users id;

0.81% Error rate ! Statistics UV Mission , Negligible !

Test use

If fault tolerance is allowed , Then it must be possible to use Hyperloglog
If fault tolerance is not allowed , Just use set or Own data type that will do

node1:6379> pfadd mykey a b c d e f g h i j  #  Create the first set of elements  mykey
(integer) 1
node1:6379> PFCOUNT mykey  #  Statistics mykey The cardinal number of elements 
(integer) 10
node1:6379> pfadd mykey2 i j z x c v n m  #  Create a second set of elements mykey2
(integer) 1
node1:6379> PFCOUNT mykey2
(integer) 8
node1:6379> pfcount mykey2 mykey
(integer) 15
node1:6379> PFMERGE mykey3 mykey mykey2 #  Combine the two groups  mykey mykey2=>mykey3 Combine 
OK
node1:6379> PFCOUNT mykey3  #  Look at the number of unions !
(integer) 15

3、bitmap Bitmap

  • Bit storage
 Interview questions :

 How to filter users is the fastest :0-1-0-1 It's the fastest .
 Count the number of infected people :0 0 1 0 0

14 100 million Chinese , set up 14 One hundred million 0, Infected, set to 1.
 Statistics user information , active 、 Inactive . Sign in 、 Not logged in . Clock in , Nail punch punch punch ! as long as 2 A state of , Both can be used. Bitmaps To deal with it .

userid status day  It's very troublesome 
​ Bitmaps Bitmap , data structure ! It's all operating bits to record , Only 0 and 1 Two states !

​ 365 God =365bit 1 byte =8bit 46 In bytes or so !
  • test

Use bitmap To record clocks from Monday to Sunday ! Monday :1 Tuesday :0 Wednesday :0 Thursday :1……


# getbit
node1:63 79> getbit sign 3   #  Check to see if you clock in on a day 
(integer) 1
node1:6379> getbit sign 6
(integer) 0

# bigcount
node1:6379> bitcount sign   #  Check to see if you are on duty   Statistical operation , Count the days of clock in 
(integer) 3

 Insert picture description here

copyright notice
author[Classmate an downstairs],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262300400026.html

Random recommended