当前位置:网站首页>Redis learning (1) -- overview and common commands

Redis learning (1) -- overview and common commands

2022-06-21 13:48:00 sunonzj

Relational database (SQL):Mysql,oracle

characteristic : Between data and data 、 Between table and field , There is a relationship between tables .

advantage : There is a relationship between the data 、 It is very convenient to add, delete, modify and query data 、 A relational database has transactional operations , Ensure data integrity .

shortcoming : Because there is a relationship between data and data , Relationships are guaranteed by a large number of underlying algorithms , It will slow down the system , Consume system resources ; Adding, deleting, modifying and checking massive data is likely to be down , maintain / Expansion will also be bad .

It is suitable for processing general data , Security .

Non relational database (NOSQL):Redis

The non relational database was originally designed to replace the relational database .

advantage : The addition, deletion, modification, query and maintenance of massive data are very easy .

shortcoming : There is no relationship between data and data , Not at a glance ; No transaction guarantees data integrity and security .

It is suitable for processing massive data , efficiency . Not necessarily safe .

Main stream NOSQL database

NoSQL The four categories of the database are as follows :

1 Key value (Key-Value) Storage database

Related products :Tokyo Cabinet/Tyrant、Redis、Voldemort、Berkeley DB

Typical applications : Content caching , Mainly used to handle high access loads with large amounts of data .

Data model : A series of key value pairs

advantage : Excellent quick query , Strong stability .

Inferiority : The stored data lacks structure

2 Column store database

  Related products :Cassandra、HBase,Riak

  Typical applications : Distributed file system

  Data model : Store as a column cluster , Store the same column of data together

  advantage : Fast search speed , High scalability , Easier to distribute

  Inferiority : Relatively limited function , Use a lot of memory to allocate , And the system will not be available for several seconds or even longer when processing the algorithm , Cause a large number of processing timeouts

3 Document database ( Eliminate )

Related products :CouchDB、MongoDb

Typical applications :Web application ( And Key-Value similar ,Value It's structured )

Data model : A series of key value pairs

advantage : Data structure requirements are not strict

Inferiority : Poor query performance , And the lack of a unified query syntax

4 graphics (Graph) database

Correlation database :Neo4J、infoGrid、infinite、Graph

Typical applications : Social networks 【 Networks 】

Data model : The graph structure

advantage : Using graph structure correlation algorithm

Inferiority : You need to compute the whole graph to get the result , It is not easy to do distributed cluster solutions . Too limited

Redis summary

Redis origin

2008 year , A start-up in Italy Merzia Launched a model based on MySQL Web site real time statistics system based on LLOOGG, But it wasn't long before the company's founders Salvatore Sanfilippo Then the MySQL Disappointed with the performance of , So he decided to do it himself LLOOGG Tailor one database , Merge on 2009 Development completed in , This database is Redis. however Salvatore Sanfilippo It's not enough to just Redis be used for LLOOGG This product , But I want more people to use it , So in the same year Salvatore Sanfilippo take Redis Open source release , And start and Redis Another major code contributor to Pieter Noordhuis Go on together Redis Development of , Until today, .

Salvatore Sanfilippo I didn't think of , In just a few years ,Redis We have a huge user base .Hacker News stay 2012 A database usage survey was released in , It turned out to be close to 12% Our company is using Redis. At home, such as Sina weibo 、 Street side net 、 Quora , Abroad is like GitHub、Stack Overflow、Flickr Are all Redis Users of .

VMware Company from 2010 Started sponsoring Redis Development of ,Salvatore Sanfilippo and Pieter Noordhuis Also in 3 The month and 5 Month join VMware, Full time development Redis.

What is? Redis

Redis Yes, it is C An open source high performance key value pair for language development (key-value) database . It can meet the storage requirements of different scenarios by providing a variety of key data types , So far, Redis The supported key value data types are as follows :

1. String type

2. Hash type

3. List the type

4. Collection types

5. Ordered set type .

Official test data :50 Individual concurrent execution 100000 A request , The speed of reading is zero 110000 Time /s, The speed of writing is 81000 Time /s. Data for reference only , There will be different results according to the server configuration .

Redis Application scenarios of

cache ( Data query 、 Short connection 、 News content 、 Product content and so on ).( Use... At most )

A list of online friends in a chat room .

Task queue .( seckill 、 Rush purchase 、12306 wait )

Application ranking .

Website visit statistics .

Data expiration processing ( It can be accurate to milliseconds )

In distributed cluster architecture session Separate .

Redis Installation and startup

Reference blog :http://localhost:8080/zjblog/toDetail?articleId=1903011210191700007

redis data type

redis Use key value pairs Save the data (map)

key: It's all strings

value: There are five types

Key name : Customize , In theory, it should not be too long, otherwise it will affect the use efficiency ( Query length from small to large ). Not too short , Be meaningful .

Redis command -String command

summary : The string type is Redis The most basic data storage type in , It's in Redis Is binary safe , This means that the data stored and retrieved by this type will be the same . stay Redis Of string type Value The maximum length of data that can be held is 512M.

Binary security has nothing to do with data security .

MySQL- Relational database , Binary is not safe .【 The statement 、 Lost data 】

assignment ( amount to map.put)

set key value: Set up key Holds the specified string value, If it's time to key If it exists, overwrite it , Always returns “OK”.

Value ( amount to map.get)

get key: obtain key Of value. If with this key The associated value It is not string Type of ,Redis The error message... Will be returned , because get The command can only be used to get String value; If it's time to key non-existent , return (nil).

get key value: First get the key Value , Then set the key Value , new value Will cover the old value.

Delete ( amount to map.remove)

del key: Delete the specified key, Return the number of affected rows .

other :

Get and modify the value

getset key value: First get the key Value , Then set the key Value .

Increasing

incr key: Specifies the key Of value An increase in atomicity 1, If it's time to key non-existent , Its initial value is 0, stay incr Then it's worth 1. If value The value of cannot be converted to an integer , Such as hello, This operation will fail and return the corresponding error message . amount to i++

Decline

decr key: Specifies the key Of value The decrease of atomicity 1, If it's time to key non-existent , Its initial value is 0, stay decr Then it's worth -1, If value The value of cannot be converted to an integer , Such as hello, The operation failed with the corresponding error . amount to i—

String concatenation

append key value: String concatenation . If it's time to key There is , In the original value Add this value after , If it doesn't exist , Then recreate a key/value

Increase the value by any value

incrby key increment: Specifies the key Of value Increase in atomicity increment, If it's time to key non-existent , Its initial value is 0, stay incrby after , The value is increment. If the value cannot be converted to an integer , It fails and an error is reported .

Decrement a value by any value

decrby key decrement: Specifies the key Of value Increase in atomicity decrement, If it's time to key non-existent , Its initial value is 0, stay incrby after , The value is -decrement. If the value cannot be converted to an integer , It fails and an error is reported .

String Usage environment : It is mainly used to preserve json Format string

Redis command -hash command

summary :Redis Medium Hash Type can be seen as having String Key and String Value Of map Containers . So this type is very suitable for storing information about value objects . Such as Username、Password etc. . If Hash It contains very few fields , Then this type of data will only occupy a small amount of disk space . every last Hash Can be stored 4294967295 Key value pairs .

assignment

hset key field value: For the specified key Set up field/value Yes ( Key value pair ).

hmset key field value field2 value2 …: Set up key In the multiple filed/value

Value

hget key field: Returns the specified key Medium field Value .

hmget key filed1 filed2 …: obtain key In the multiple filed Value

hgetall key: obtain key All in filed-value

Delete

hdel key field field..: One or more fields can be deleted , The return value is the number of deleted fields .

del key: Delete the whole

add number

hincrby key field increment: Set up key in filed The value of the increase increment

Other commands

hexists key field: Judge designated key Medium filed Whether there is

hlen key: obtain key It contains filed The number of

hkeys kye: Get all fields

hvals key: Get all value

keys * Query all key

Redis command -list command

summary :dis in ,List The type is a list of strings in insertion order . It is the same as the common linked list in data structure , We can have it on the head (left) And the tail (right) Add new elements . When inserting , If the key doesn't exist ,Redis A new linked list will be created for the key . On the contrary , If all elements in the list are removed , Then the key will also be removed from the database .List The maximum number of elements that can be contained in is 4294967295.

From the efficiency perspective of element insertion and deletion , If we insert or delete elements at both ends of the list , This will be a very efficient operation , Even if millions of records have been stored in the linked list , This can also be done in constant time . However, it should be noted that , If the element insert or delete operation is applied to the middle of the list , That would be very inefficient . I believe that for developers with good data structure foundation , It's not hard to understand .

assignment ( Add... At both ends )

lpush key values1 values2 …: At the designated key The associated list Head insert all values. If it's time to key non-existent , This command creates an associated with the before inserting key Associated empty list , Then insert the data into the head of the list . Insert the success , Returns the number of elements .

rpush key values1 values2…: In the list Add elements to the tail of .

Value ( view list )

lrange key start end: Get the list from start To end The value of the element ,start、end from 0 Start counting , It can also be negative , if -1 Then identify the elements at the end of the linked list .-2 It means the next to last , And so on ..

Delete ( Pop at both ends )

lpop key: Return and pop up the specified key The first element in the associated list , The head element . If it's time to key non-existent , return nil; If it exists, the header element in the linked list will be returned

rpop key: Single out elements from the tail .

Get the number of elements in the list

llen key: Returns the specified key The number of elements in the associated list .

Delete an element ( Low efficiency )

lrem key count value: Delete count The values are value The elements of , If count Greater than 0, Traverse from head to tail and delete count The values are value The elements of , If count Less than 0, Then traverse from the tail to the head and delete . If count be equal to 0, Then delete all the equals in the list value The elements of .

Replace element by index ( Low efficiency )

lset key index value: Set... In the list index The element value of the subscript ,0 Represents the head element of the list ,-1 Represents the end element of the list . If the operation chain table's subscript does not exist, throw an exception .

Before indexing / Insert elements after ( Low efficiency )

linsert key before|after pivot value: stay pivot Insert elements before and after value This element .

The extension command

rpoplpush resource destination: take resource The tail element in the linked list pops up and is added to destination Head .

rpoplpush resource resource: take resource The tail element in the linked list pops up and is added to resource Head .( Cyclic operation )

Redis command -set command

summary :Set yes String Unordered collection of type . Collection members are unique , This means that duplicate data cannot appear in the collection . The maximum number of members in the collection is 232 - 1 (4294967295, Each collection can store 40 More than 100 million members ).

add to / Remove elements

sadd key value value1…: towards set Add data to , If it's time to key If the value already exists, it will not be added repeatedly .

srem key members members1..: Delete set The member named in .

Value

smembers key: obtain set All elements in

sismember key member: Determine whether the element specified in the parameter exists ,1 Indicates presence ,0 Indicates that does not exist or that key It doesn't exist in itself .( No matter how many elements there are in the collection, you can return results very quickly ).

Set operations

sdiff key1 key2 …: Subtraction operation , return kye1 And key2 The difference between the members of , And with the key The order of . That is, the difference set is returned .

sinter key1 key2 …: Return to intersection

sunion key1 key2 ..: Back to Union .

The extension command

scard key: obtain set Number of elements in

srandmember key: Returns a random element

sdiffstore destination key1 key2..: take key1、key2 The members of the difference are stored in destination On

sinterstore destination key1 key2..: Store the returned communication in destination On

sunionstore destination key1 key2..: Store the returned Union in destination On

Redis command - Orderly set command (zset)

summary :Redis An ordered set is the same as a set string Collection of type elements , And duplicate members are not allowed . The difference is that each element is associated with a double Score of type .redis It's the scores that sort the members of a collection from small to large .

Members of an ordered set are unique , But fractions (score) But it can be repeated .

Orderly set aggregate : Orderly , No repetition . It is specially used to make leaderboards

Additive elements

zadd key score member score2 member2 …: Put all members and their scores in sorted-set in . If the element already exists, the original score will be replaced by the new score . The return value is the number of new elements added to the collection , Does not contain elements that have existed before .

Get elements

zscore key member: Returns the score of the specified member .

Remove elements

zrem key member member…: Remove the specified member from the collection , You can specify multiple .

Range queries ( Check out the order )

zrange key start end [withscores] : Gets the subscript in the collection as start-end Members of ,withscores Parameter indicates that the returned member contains its score .( Scores range from small to large )

zrevrange key start end [withscores] : Gets the subscript in the collection as start-end Members of ,withscores Parameter indicates that the returned member contains its score .( The scores are arranged from big to small )

zremrangebyrank key start stop: Delete elements... According to the ranking range

zremrangebyscore key min max  : Delete elements... According to the score range

The extension command

zrangebyscore key min max [withscores] [limit offset count]: The return score is in [min,max] And rank them in order of score from low to high .[withscores]: Show scores ;[limit offset count]:offset, Indicates that the footmark is offset The element starts and returns count Members .

zincrby key increment member: Set the increased score of the specified member . Change the score when returning the value .

zcount key min max: Get points in [min,max] Member between .

zrank key member: Returns the ranking of members in the collection . Indexes ( From small to large ).

zrevrank key member: Returns the ranking of members in the collection . Indexes ( From big to small ).

Redis command - General Command

keys pattern: Get all and pattern Matching key, Return to all with the key Matching keys.* Represents any one or more characters ,? Represents any character .

del key1 key2 ..: Delete specified key.

exists key: Judge that key Whether there is ,1 On behalf of there ,0 nonexistence .

rename key newkey: For the current key rename

expire key time: Set expiration time , Company : second . Delete upon expiration .

ttl key: Get the key The timeout time left , If no timeout is set , return -1. If you return -2 Indicates that the timeout does not exist .

type key: Get specified key The type of . This command will return... In the form of a string . The string returned is string、list、set、Hash、zset. If key There is no return none.

redis Server command

ping: Test if the connection is alive .ping Successfully returns PONG;

echo: Print something on the command line .echo “HELLO WORLD!”;

select: Select database .redis Database number 【0-15】, choice 16 It's a false report ;

quit: Exit connection ;

dbsize: Return to the current database key Number of ;

info: Get server information and statistics ;

原网站

版权声明
本文为[sunonzj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211341493049.html