Redis brief introduction
REmote DIctionary Server(Redis) It's a key-value The storage system .Redis Is an open source use ANSI C Language writing 、 comply with BSD agreement 、 Support network 、 Log type that can be memory based or persistent 、Key-Value database , And provide multilingual API. It is often referred to as a data structure server , Because of the value （value） It can be character string (String), Hash (Hash), list (list), aggregate (sets) and Ordered set (sorted sets) Other types .
Redis And others key - value Cache products have the following three characteristics ：
- Redis Support data persistence , The data in memory can be saved on disk , When you restart, you can load it again for use .
- Redis It's not just about supporting simple key-value Data of type , It also provides list,set,zset,hash Such as data structure storage .
- Redis Support data backup , namely master-slave Mode data backup .
- Extremely high performance – Redis The speed at which you can read is 110000 Time /s, The speed of writing is 81000 Time /s .
- Rich data types – Redis Supporting binary cases Strings, Lists, Hashes, Sets And Ordered Sets Data type operations .
- atom – Redis All operations of are atomic , It means either successful execution or failure and no execution at all . Individual operations are atomic . Multiple operations also support transactions , Atomicity , adopt MULTI and EXEC Package the instructions .
- Rich features – Redis And support publish/subscribe, notice , key Expiration and so on .
Redis And others key-value What's the difference between storage ？
- Redis They have more complex data structures and provide atomic operations on them , This is a different evolutionary path from other databases .Redis All data types are based on basic data structure and transparent to programmers , There is no need for additional abstraction .
- Redis Run in memory but persist to disk , So we need to balance memory when we read and write different data sets at high speed , Because the amount of data cannot be larger than the hardware memory . Another advantage of in memory databases is , Compared to the same complex data structure on disk , It's very easy to operate in memory , such Redis Can do a lot of internal complexity of things . meanwhile , In terms of disk format, they are generated in a compact and additional way , Because they don't need random interviews .
Ubuntu apt Command to install
- stay Ubuntu System installation Redis You can use the following command :
sudo apt update# sudo apt install redis-server
- start-up Redis
- see redis Whether to start ？
- The above command will open the following terminals ：
- 127.0.0.1 It's local IP ,6379 yes redis Service port . Now let's type in PING command .
redis 127.0.0.1:6379> pingPONG
The above shows that we have successfully installed redis.
Redis To configure
Redis The configuration file is located in Redis Installation directory , The file named redis.conf(Windows be known as redis.windows.conf).
You can go through CONFIG Command to view or set configuration items .
- grammar Redis CONFIG The command format is as follows ：
redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
redis 127.0.0.1:6379> CONFIG GET loglevel1) "loglevel"2) "notice"
- Use * Get all configuration items ：
redis 127.0.0.1:6379> CONFIG GET * 1) "dbfilename" 2) "dump.rdb" 3) "requirepass" 4) "" 5) "masterauth" 6) "" 7) "unixsocket" 8) "" 9) "logfile" 10) "" 11) "pidfile" 12) "/var/run/redis.pid" 13) "maxmemory" 14) "0" 15) "maxmemory-samples" 16) "3" 17) "timeout" 18) "0" 19) "tcp-keepalive" 20) "0" 21) "auto-aof-rewrite-percentage" 22) "100" 23) "auto-aof-rewrite-min-size" 24) "67108864" 25) "hash-max-ziplist-entries" 26) "512" 27) "hash-max-ziplist-value" 28) "64" 29) "list-max-ziplist-entries" 30) "512" 31) "list-max-ziplist-value" 32) "64" 33) "set-max-intset-entries" 34) "512" 35) "zset-max-ziplist-entries" 36) "128" 37) "zset-max-ziplist-value" 38) "64" 39) "hll-sparse-max-bytes" 40) "3000" 41) "lua-time-limit" 42) "5000" 43) "slowlog-log-slower-than" 44) "10000" 45) "latency-monitor-threshold" 46) "0" 47) "slowlog-max-len" 48) "128" 49) "port" 50) "6379" 51) "tcp-backlog" 52) "511" 53) "databases" 54) "16" 55) "repl-ping-slave-period" 56) "10" 57) "repl-timeout" 58) "60" 59) "repl-backlog-size" 60) "1048576" 61) "repl-backlog-ttl" 62) "3600" 63) "maxclients" 64) "4064" 65) "watchdog-period" 66) "0" 67) "slave-priority" 68) "100" 69) "min-slaves-to-write" 70) "0" 71) "min-slaves-max-lag" 72) "10" 73) "hz" 74) "10" 75) "no-appendfsync-on-rewrite" 76) "no" 77) "slave-serve-stale-data" 78) "yes" 79) "slave-read-only" 80) "yes" 81) "stop-writes-on-bgsave-error" 82) "yes" 83) "daemonize" 84) "no" 85) "rdbcompression" 86) "yes" 87) "rdbchecksum" 88) "yes" 89) "activerehashing" 90) "yes" 91) "repl-disable-tcp-nodelay" 92) "no" 93) "aof-rewrite-incremental-fsync" 94) "yes" 95) "appendonly" 96) "no" 97) "dir" 98) "/home/deepak/Downloads/redis-2.8.13/src" 99) "maxmemory-policy"100) "volatile-lru"101) "appendfsync"102) "everysec"103) "save"104) "3600 1 300 100 60 10000"105) "loglevel"106) "notice"107) "client-output-buffer-limit"108) "normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60"109) "unixsocketperm"110) "0"111) "slaveof"112) ""113) "notify-keyspace-events"114) ""115) "bind"116) ""
Edit the configuration
You can modify it redis.conf Document or use CONFIG set Command to modify the configuration .
CONFIG SET Command basic syntax ：
redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
redis 127.0.0.1:6379> CONFIG SET loglevel "notice"OKredis 127.0.0.1:6379> CONFIG GET loglevel1) "loglevel"2) "notice"
- redis.conf The configuration items are described as follows ：
|Serial number||Configuration item||explain|
||Redis The default is not to run as a daemon , This configuration item can be modified , Use yes Enable daemons （Windows The configuration of the daemons is not supported no ）|
||When Redis Run as a daemon ,Redis By default the pid write in /var/run/redis.pid file , Can pass pidfile Appoint|
|| Appoint Redis Listening port , The default port is 6379, Why choose 6379 As default port ?,6379 On the phone button MERZ The corresponding number , and MERZ From the Italian singer Alessia Merz Name .MERZ For a long time Redis author antirez And his friends as a byword for stupidity . later Redis The author is developing Redis This port is selected when .
——Alessia Merz It's an Italian dancer 、 actress . Redis author Antirez In my early years, I watched TV programs , Think Merz Some of the words on the show are silly ,Antirez Like to make “ stem ” It is used to communicate with friends , So I made a word “MERZ”, To describe stupidity , And “stupid” The meaning is the same .
—— later Antirez redefined “MERZ” , Describe ” It has high technical value , It contains skills 、 Patience and labor , But still keep it simple “.
—— Here we are Redis When you select a number as the default port number ,Antirez I didn't think much about , hold “MERZ” The corresponding number on the phone keyboard 6379 I used it .
||The bound host address|
||Close the connection after how many seconds the client is idle , If specified as 0 , Indicates that the feature is turned off|
||Specifies the logging level ,Redis There are four levels supported ：debug、verbose、notice、warning, The default is notice|
||Logging mode , The default is standard output , If configured Redis Run for daemon mode , This is configured for logging as standard output , The log will be sent to /dev/null|
||Set the number of databases , The default database is 0, have access to SELECT The command specifies the database on the connection id|
save 900 1
save 300 10
save 60 10000
respectively 900 second （15 minute ） There are 1 A change ,300 second （5 minute ） There are 10 Changes and 60 In seconds 10000 A change .
|Specify how long , How many update operations are there , Synchronize the data to the data file , Multiple conditions can be used|
||Specifies whether data is compressed when stored to a local database , The default is yes,Redis use LZF Compress , If in order to save money CPU Time , This option can be turned off , But it can make the database files huge|
||Specifies the local database file name , The default value is dump.rdb|
||Specifies the local database hosting directory|
||Set when the native is slave The service , Set up master Service IP Address and port , stay Redis Startup time , It will automatically follow master Data synchronization|
||When master When the service is password protected ,slav Service connection master Password|
||Set up Redis Connect the password , If the connection password is configured , The client is connecting Redis Need to go through AUTH Command provide password , Off by default|
||Sets the maximum number of client connections at one time , Default limit ,Redis The number of client connections that can be opened simultaneously is Redis The maximum number of file descriptors that a process can open , If you set maxclients 0, No restrictions . When the number of client connections reaches the limit ,Redis The new connection is closed and returned to the client max number of clients reached error message|
||Appoint Redis Maximum memory limit ,Redis Data is loaded into memory at startup , After reaching the maximum memory ,Redis It will first try to clear those that are due or are about to expire Key, When this method is handled after , Still reaches the maximum memory setting , Will no longer be able to write , But you can still do a read .Redis new vm Mechanism , Will be able to Key Storage memory ,Value Will be stored in a swap District|
||Specifies whether to log after each update operation ,Redis By default, data is written asynchronously to disk , If you don't turn it on , Data may be lost for a period of time during a power outage . because redis The itself synchronization data file is pressed above save Condition to synchronize , So some data will only exist in memory for a while . The default is no|
||Specifies the file name of the update log , The default is appendonly.aof|
||Specifies an update log condition , share 3 Optional values ：no： Means that the operating system synchronizes the data cache to disk （ fast ）always： Represents a manual call after each update operation fsync() Write data to disk （ slow , Security ）everysec： That means once per second （ compromise , The default value is ）|
||Specifies whether the virtual memory mechanism is enabled , The default value is no, A brief introduction ,VM The mechanism stores data in pages , from Redis Cold data for less visited pages swap To disk , Pages with multiple accesses are automatically swapped out from disk to memory （ I will analyze it carefully in the following articles Redis Of VM Mechanism ）|
||Virtual memory file path , The default value is /tmp/redis.swap, Not more than one Redis The instance Shared|
||I'm going to make everything greater than vm-max-memory Is stored in virtual memory , No matter what vm-max-memory Set up small , All index data is stored in memory (Redis Index data of Namely keys), in other words , When vm-max-memory Set to 0 When , It's all value Both exist on disk . The default value is 0|
||Redis swap The file is divided into many parts page, An object can be stored in more than one page above , But a page Can't be Shared by multiple objects ,vm-page-size It's based on storage The data size is set , The authors suggest storing many small objects ,page The size is best set to 32 perhaps 64bytes; If you store large objects , You can use a larger one page, If not sure , Just use the default values|
||Set up swap In the document page Number , Because the page table （ One that indicates that a page is free or in use bitmap） It's in memory ,, Each on disk 8 individual pages Will consume 1byte Of memory .|
||Set access swap Number of threads in the file , It is best not to exceed the audit of the machine , If set to 0, So all right swap The operation of the file is serial , May cause a relatively long delay . The default value is 4|
||Set when to reply to the client , Whether to combine smaller packages into a single package , On by default|
||Specifies when a certain number or maximum of elements exceeds a certain threshold , A special hash algorithm is used|
||Specifies whether to activate the reset hash , On by default （ In the introduction Redis The hash algorithm is introduced in detail ）|
||Specifies that additional configuration files are included , More than one can be on the same host Redis The same configuration file is used between instances , At the same time, each instance has its own specific configuration|
Redis data type
Redis Five data types are supported ：string（ character string ）,hash（ Hash ）,list（ list ）,set（ aggregate ） And zset(sorted set： Ordered set ).
String（ character string ）
string yes redis Most basic types , You can understand that Memcached As like as two peas , One key Corresponding to one value.
string Type is binary safe . intend redis Of string Can contain any data . such as jpg Picture or serialized object .
string The type is Redis Basic data types ,string The maximum value of type can store 512MB.
redis 127.0.0.1:6379> SET runoob "huahua"OKredis 127.0.0.1:6379> GET runoob"huahua"
In the above example, we used Redis Of SET and GET command . The key is runoob, The corresponding value is huahua.
Be careful ： Maximum storage of one key 512MB.
Redis Detailed explanation of string command
The following table lists the common redis String command ：
|Serial number||Command and description|
|1||SET key value Set the specified key Value|
|2||GET key Get specified key Value .|
|3||GETRANGE key start end return key The child character of the string value in|
|4||GETSET key value Will be given key The value of the set value , And back to key The old value (old value).|
|5||GETBIT key offset Yes key String value stored , Gets the bit on the specified offset (bit).|
|6||[MGET key1 key2..] Get all ( One or more ) Given key Value .|
|7||SETBIT key offset value Yes key String value stored , Sets or clears the bit on the specified offset (bit).|
|8||SETEX key seconds value Will value value Related to key , And will key The expiration time of is set to seconds ( In seconds ).|
|9||SETNX key value Only in key Set when not present key Value .|
|10||SETRANGE key offset value use value Parameter override given key String value stored , From the offset offset Start .|
|11||STRLEN key return key The length of the stored string value .|
|12||[MSET key value key value ...] Set one or more... At the same time key-value Yes .|
|13||[MSETNX key value key value ...] Set one or more... At the same time key-value Yes , If and only if all given key It doesn't exist .|
|14||PSETEX key milliseconds value This command and SETEX Command similar , But it's set in milliseconds key Survival time , Not like it SETEX Order that , In seconds .|
|15||INCR key take key The value of the number stored in is increased by one .|
|16||INCRBY key increment take key The stored value plus the given increment value （increment） .|
|17||INCRBYFLOAT key increment take key The stored value plus the given floating-point delta value （increment） .|
|18||DECR key take key Subtract one from the number stored in .|
|19||DECRBY key decrement key The stored value minus the given decrement value （decrement） .|
|20||APPEND key value If key Already exists and is a string , APPEND The order will specify value Append to the key Original value （value） At the end of .|
Hash（ Hash ）
Redis hash It's a key value (key=>value) The collection .
Redis hash It's a string Type of field and value Mapping table ,hash Ideal for storing objects .
DEL runoob Used to delete used in previous tests key, Otherwise, it will report a mistake ：(error) WRONGTYPE Operation against a key holding the wrong kind of value
redis 127.0.0.1:6379> DEL runoobredis 127.0.0.1:6379> HMSET runoob field1 "Hello" field2 "World""OK"redis 127.0.0.1:6379> HGET runoob field1"Hello"redis 127.0.0.1:6379> HGET runoob field2"World"
In the example, we use Redis HMSET, HGET command ,HMSET Set up two field=>value Yes , HGET Get corresponding field Corresponding value.
Every hash Can be stored 232 -1 Key value pair （40 More than ）.
Redis hash Detailed command
The following table lists them redis hash Basic related commands ：
|Serial number||Command and description|
|1||[HDEL key field1 field2] Delete one or more hash table fields|
|2||HEXISTS key field Look at the hash table key in , Whether the specified field exists .|
|3||HGET key field Gets the value of the specified field stored in the hash table .|
|4||HGETALL key Gets the specified in the hash table key All fields and values of|
|5||HINCRBY key field increment Hash table key The integer value of the specified field in plus the increment increment .|
|6||HINCRBYFLOAT key field increment Hash table key The floating-point value of the specified field in plus the increment increment .|
|7||HKEYS key Get all the fields in the hash table|
|8||HLEN key Get the number of fields in the hash table|
|9||[HMGET key field1 field2] Get the value of all the given fields|
|10||[HMSET key field1 value1 field2 value2 ] There will be more than one field-value ( Domain - value ) Set to hash table key in .|
|11||HSET key field value Hash table key In the field field The value of the set value .|
|12||HSETNX key field value Only in the fields field When there is no , Set the value of the hash table field .|
|13||HVALS key Get all values in hash table .|
|14||[HSCAN key cursor MATCH pattern] [COUNT count] Iterate over the key value pairs in the hash table .|
List（ list ）
Redis List is a simple list of strings , Sort by insertion order . You can add an element to the head of the list （ On the left ） Or tail （ On the right ）.
redis 127.0.0.1:6379> DEL runoobredis 127.0.0.1:6379> lpush runoob redis(integer) 1redis 127.0.0.1:6379> lpush runoob mongodb(integer) 2redis 127.0.0.1:6379> lpush runoob rabitmq(integer) 3redis 127.0.0.1:6379> lrange runoob 0 101) "rabitmq"2) "mongodb"3) "redis"redis 127.0.0.1:6379>
List can be stored at most 232 - 1 Elements (4294967295, Each list can be stored 40 More than ).
Redis List command details
The following table lists the list related basic commands ：
|Serial number||Command and description|
|1||[BLPOP key1 key2 ] timeout Move out and get the first element of the list , If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .|
|2||[BRPOP key1 key2 ] timeout Move out and get the last element of the list , If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .|
|3||BRPOPLPUSH source destination timeout 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, it will block the list until the wait timeout or pop-up elements are found .|
|4||LINDEX key index Get the elements in the list by index|
|5||LINSERT key BEFORE|AFTER pivot value Insert an element before or after a list element|
|6||LLEN key Get list length|
|7||LPOP key Move out and get the first element of the list|
|8||[LPUSH key value1 value2] Insert one or more values into the list header|
|9||LPUSHX key value Insert a value into the existing list header|
|10||LRANGE key start stop Get the elements in the specified range of the list|
|11||LREM key count value Remove list elements|
|12||LSET key index value Set the value of the list element through the index|
|13||LTRIM key start stop Trim a list (trim), That is to say , Let the list keep only the elements in the specified range , Elements that are not in the specified range will be removed .|
|14||RPOP key Remove the last element of the list , The return value is the removed element .|
|15||RPOPLPUSH source destination Remove the last element of the list , And add the element to another list and return|
|16||[RPUSH key value1 value2] Add one or more values... To the list|
|17||RPUSHX key value Add value to existing list|
Set（ aggregate ）
Redis Of Set yes string Unordered collection of type .
Collections are implemented through hash tables , So add the , Delete , The complexity of searching is O(1).
Add one string Element to key Corresponding set Collection , Successfully returns 1, If the element has already returned in the collection 0.
sadd key member
redis 127.0.0.1:6379> DEL runoobredis 127.0.0.1:6379> sadd runoob redis(integer) 1redis 127.0.0.1:6379> sadd runoob mongodb(integer) 1redis 127.0.0.1:6379> sadd runoob rabitmq(integer) 1redis 127.0.0.1:6379> sadd runoob rabitmq(integer) 0redis 127.0.0.1:6379> smembers runoob1) "redis"2) "rabitmq"3) "mongodb"
Be careful ： In the example above rabitmq Added twice , But according to the uniqueness of the elements in the set , The second inserted element will be ignored .
The maximum number of members in the collection is 232 - 1(4294967295, Each collection can store 40 More than 100 million members ).
Redis Assemble orders
The following table lists them Redis Set basic commands ：
|Serial number||Command and description|
|1||[SADD key member1 member2] Add one or more members to the collection|
|2||SCARD key Get the number of members of the collection|
|3||[SDIFF key1 key2] Returns the difference between the first set and the others .|
|4||[SDIFFSTORE destination key1 key2] Returns the difference set of a given set and stores it in destination in|
|5||[SINTER key1 key2] Returns the intersection of a given set|
|6||[SINTERSTORE destination key1 key2] Returns the intersection of a given set and stores it in destination in|
|7||SISMEMBER key member Judge member Is the element a collection key Members of|
|8||SMEMBERS key Returns all members of the collection|
|9||SMOVE source destination member take member Elements from source The assembly moves to destination aggregate|
|10||SPOP key Remove and return a random element from the collection|
|11||[SRANDMEMBER key count] Returns one or more random numbers in a set|
|12||[SREM key member1 member2] Remove one or more members of the collection|
|13||[SUNION key1 key2] Returns the union of all given sets|
|14||[SUNIONSTORE destination key1 key2] The union of all given sets is stored in destination Collection|
|15||[SSCAN key cursor MATCH pattern] [COUNT count] Iterate over the elements in the collection|
zset(sorted set： Ordered set )
Redis zset and set The same is true. 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 .
zset Members of are unique , But fractions (score) But it can be repeated .
Add elements to the collection , Update corresponding if element exists in collection score
zadd key score member
redis 127.0.0.1:6379> DEL runoobredis 127.0.0.1:6379> zadd runoob 0 redis(integer) 1redis 127.0.0.1:6379> zadd runoob 0 mongodb(integer) 1redis 127.0.0.1:6379> zadd runoob 0 rabitmq(integer) 1redis 127.0.0.1:6379> zadd runoob 0 rabitmq(integer) 0redis 127.0.0.1:6379> > ZRANGEBYSCORE runoob 0 10001) "mongodb"2) "rabitmq"3) "redis"
Redis To assemble orders in order
The following table lists them redis The basic command of ordered sets :
|Serial number||Command and description|
|1||[ZADD key score1 member1 score2 member2] Add one or more members... To an ordered collection , Or update scores of existing members|
|2||ZCARD key Get the number of members of the ordered set|
|3||ZCOUNT key min max Calculates the number of members of a specified interval fraction in an ordered set|
|4||ZINCRBY key increment member Add the increment... To the score of the specified member in the ordered set increment|
|5||[ZINTERSTORE destination numkeys key key ...] Calculates the intersection of a given ordered set or sets and stores the result set in a new ordered set destination in|
|6||ZLEXCOUNT key min max Computes the number of members in the specified dictionary interval in an ordered collection|
|7||[ZRANGE key start stop WITHSCORES] Return the members in the specified interval of the ordered set through the index interval|
|8||[ZRANGEBYLEX key min max LIMIT offset count] Returns the members of an ordered set through a dictionary interval|
|9||[ZRANGEBYSCORE key min max WITHSCORES] [LIMIT] Returns the members of an ordered set in a specified interval through scores|
|10||ZRANK key member Returns the index of a specified member in an ordered collection|
|11||[ZREM key member member ...] Remove one or more members of an ordered collection|
|12||ZREMRANGEBYLEX key min max Remove all members of a given dictionary interval from an ordered set|
|13||ZREMRANGEBYRANK key start stop Remove all members of a given rank range from an ordered set|
|14||ZREMRANGEBYSCORE key min max Remove all members of a given fraction interval from an ordered set|
|15||[ZREVRANGE key start stop WITHSCORES] Returns the members of a specified interval in an ordered set , Through the index , Scores go from high to low|
|16||[ZREVRANGEBYSCORE key max min WITHSCORES] Returns the members of the specified score range in an ordered set , Rank scores from high to low|
|17||ZREVRANK key member Returns the rank of a specified member in an ordered set , Members of an ordered set are decremented by fractions ( From big to small ) Sort|
|18||ZSCORE key member Back to the ordered set , The score of a member|
|19||[ZUNIONSTORE destination numkeys key key ...] Computes the union of a given ordered set or sets , And store it in the new key in|
|20||[ZSCAN key cursor MATCH pattern] [COUNT count] Iterate over elements in an ordered set （ Include element members and element scores ）|
Application scenarios of various data types
|String( character string )||Binary security||Can contain any data , such as jpg Picture or serialized object , Maximum storage of one key 512M||---|
|Hash( Dictionaries )||Key value pair set , In programming language Map type||Suitable for storing objects , And it can be like in a database update Only one property value can be modified for one property (Memcached The entire string needs to be taken out and deserialized into an object, and then serialized and saved )||Storage 、 Read 、 Modify user properties|
|List( list )||Linked list ( Double linked list )||Additions and deletions quickly , Provides for manipulating a certain element API||1, Latest news ranking and other functions ( For example, the timeline of the circle of friends ) 2, Message queue|
|Set( aggregate )||Hash table implementation , Elements do not repeat||1、 add to 、 Delete , The complexity of searching is O(1) 2、 Provides intersection for sets 、 Combine 、 Subtraction and so on||1、 Common friends 2、 Using uniqueness , Count all the independent websites visited ip 3、 When friends recommend , according to tag Find the intersection , More than a certain threshold can be recommended|
|Sorted Set( Ordered set )||take Set Add a weight parameter to the element in score, Element press score Arrange in order||When data is inserted into a collection , A natural sequence has been made|
Redis The command is used in the redis Perform operations on the service .
To be in redis Executing commands on a service requires a redis client .Redis The client downloaded before us redis In the installation package of .
Redis The basic syntax of the client is ：