New people into the pit Redis will vomit blood summary
What is Redis
Redis is an open source, high-performance key-value storage system developed in C language, which can be approximately understood as Java Map. Redis is a NOSQL in-memory database. Its full name is Not Only SQL. In other words, it is a non-relational database, which is a good supplement to the relational database. It differs from traditional MySQL and Oracle in that it greatly improves the read and write speed by reading and writing data in memory. It can be said that Redis is an indispensable part of the database solution to solve a series of problems such as high concurrency, high availability, high scalability, big data storage and so on.
It has the following characteristics:
1. Redis supports persistent data, which can keep the data in memory in disk, and can be loaded again for use when restarting. 2. Redis not only supports simple key-value type data, but also provides the storage of string, list, set, sortedSet, hash and other data structures. 3. Redis supports data backup, namely, data backup in master-slave mode.
Redis has five key value types:
- String character type
- Hash Hash type
- List List type
- Set set type
- Sortedset Type of an ordered collection
This article will be based on Redis5.0 as an example to introduce the use of Redis some related commands and stepped on the pit
Ii. Installation and startup of Redis
Environment to prepare
- CentOS7 (Development Tools not installed)
- Redis5.0 -rc3. Tar. Gz
The installation tutorial can be found here: www.cnblogs.com/ECJTUACM-87…
Online environment
The official website seems to offer an online Redis platform, linked here: try.redis.io/
Redis start
The front-end start
After installation according to the tutorial I provided, we just need to enter the command redis-server, the interface is as follows:
Front end stop start
- Force shutdown: Ctrl+ C
- Normal shutdown [root@sakura]# redis-cli shutdown
The back-end start
Because Redis does not work alone in practice, the IP address and port number in the startup and shutdown mode can be changed in the configuration file, which will be changed below.
Start the way
- Copy the redis. Conf file in the decompressed redis source package to the bin directory. Just copy and paste it
- Conf file, change daemonize to yes(vi redis.conf, :/daemonize search).
- Redis. command line redis-server redis.conf(start with configuration file)
- Check whether the startup is successful. Command line ps – aux | grep redis (direct view redis process)
If you’ve followed the tutorial I’ve provided, this process can be ignored
Close the way
- Forcibly disable: kill -9 PID
- Normal shutdown :redis-cli -h IP address -p port number (default port number is 6379) shutdown
In projects, it is recommended to use normal shutdown. If redis is used as a cache, the data is stored in memory. If redis is turned off normally, the memory data will be persisted locally and then closed. If the shutdown is forced, persistent operations are not performed, and some data may be lost.
The Redis client starts
Start client command :[root@sakura]# redis-cli -h IP address -p port number
Since the default IP is 127.0.0.1 and port is 6379, all we need to do is type the command redis-cli
Exit :127.0.0.1:6379> quit
Explanation of Redis data types and common commands
1, Redis – String
String Usage environment: Mainly used to save the string in JSON format
The assignment
Set key value: Sets the key to hold the specified string value, overwrites the key if it exists, always returns “OK”, if given the same key, the new value overwrites the old value
example:
127.0.0.1:6379> set username zhangsan
OK
Copy the code
The values
Get key: obtains the value of the key. If the value associated with the key is not a string, redis will return an error because the get command can only be used to get a string value. If the key does not exist, return nil
example:
127.0.0.1:6379 > get the username "zhangsan"Copy the code
delete
Del key: deletes the specified key. The returned value is a number, indicating that several pieces of data are deleted
example:
127.0.0.1:6379> del username
(integer) 1
Copy the code
extension
Getset Key Value: obtains the key value and then sets the key value
example:
127.0.0.1:6379> getset username zhangsan
(nil)
127.0.0.1:6379> keys *
1) "username"
127.0.0.1:6379> get username
"zhangsan"
Copy the code
Incr key: increals the value of the specified key atomically by 1. If the key does not exist, the initial value is 0, and the value after incr is 1. If the value of the key cannot be converted to an integer, such as Hello, this operation fails and returns an error message, equivalent to ++. When the counter)
example:
127.0.0.1:6379> set age 18
OK
127.0.0.1:6379> incr age
(integer) 19
Copy the code
Decr key: decrement the atomicity of the value of the specified key by 1. If the key does not exist, its initial value is 0, and the value after incr is -1. If the value of value cannot be converted to an integer, such as Hello, this operation fails and returns an error message, equivalent to — I
example:
127.0.0.1:6379> set age 18
OK
127.0.0.1:6379> decr age
(integer) 17
Copy the code
Append Key Value: a concatenated string. If the key exists, the value is appended to the original value. If the key does not exist, a new key/value is created
example:
127.0.0.1:6379> Set information hel OK 127.0.0.1:6379> Append information LO (INTEGER) 5 127.0.0.1:6379> Get information "hello"Copy the code
Incrby and decrby: This operation can be performed only for numeric strings. Incrby key Value adds value to the original key value, and decrby key value decreases value to the original key value
example:
127.0.0.1:6379> get age
"17"
127.0.0.1:6379> incrby age 10
(integer) 27
127.0.0.1:6379> decrby age 10
(integer) 17
127.0.0.1:6379> get information
"hello"
127.0.0.1:6379> incrby information 10
(error) ERR value is not an integer or out of range
127.0.0.1:6379> decrby information 10
(error) ERR value is not an integer or out of range
Copy the code
2, Redis hash
The hash type in Redis can be regarded as a map container with string keys and string values, so it is very suitable for storing information about value objects. Such as username, password, and age. If the hash contains very few fields, that type of data will also take up very little disk space. Each hash can store 4,294,967,295 key-value pairs.
Hash features: Occupies very little disk space
Assignment:
Hset key field Value: Sets the field/value pair for the specified key.
example:
127.0.0.1:6379> hset key1 field1 123
(integer) 1
Copy the code
hmset key field value[field2 value2…] : Sets multiple fields/values in the key
example:
127.0.0.1:6379> hmset aaa name kitty age 20
OK
Copy the code
Values:
Hget Key filed: Field value of the specified key
example:
127.0.0.1:6379> hget key1 field1
"123"
Copy the code
hmget key filed1 field2… : Gets the values of multiple fields in the key
example:
127.0.0.1:6379> hmget aaa name age
1) "kitty"
2) "20"
Copy the code
Hgetall key: Gets all field-value2s in the key
example:
127.0.0.1:6379> hgetall aaa
1) "name"
2) "kitty"
3) "age"
4) "20"
Copy the code
delete
hdel key field[field…] : One or more fields can be deleted. The return value is the number of fields to be deleted
example:
127.0.0.1:6379> hdel key1 field1
(integer) 1
Copy the code
Del key: Deletes the entire list
example:
127.0.0.1:6379> del aaa
(integer) 1
Copy the code
Increase the number
Hincrby Key field increment: Increments the field in the key, for example, age by 20
example:
127.0.0.1:6379> hmset aaa name kitty age 20
OK
127.0.0.1:6379> hincrby aaa age 20
(integer) 40
Copy the code
The extension command
Hexists Key Field: checks whether the field in the specified key exists
example:
127.0.0.1:6379> hexists aaa name
(integer) 1
127.0.0.1:6379> hexists aaa aaaa
(integer) 0
Copy the code
Hlen key: Gets the number of fields that the key contains
example:
127.0.0.1:6379> hlen aaa
(integer) 2
Copy the code
Hkeys key: Retrieves all fields
example:
127.0.0.1:6379> hkeys aaa
1) "name"
2) "age"
Copy the code
3, Redis – the list
In Redis, list is selected as a linked list, because in Redis operation, the most operation is to add and delete elements
The assignment
lpush key value [value1 value2 …] Inserts all values into the list header associated with the specified key. If the key does not exist, this command creates an empty list associated with the key before inserting it. After inserting data into the list header, the number of elements is returned.
example:
127.0.0.1:6379> Lpush score1 12 3 4 5 (integer) 5Copy the code
rpush key value [value1 value2 …] Add the element at the end of the list
example:
127.0.0.1:6379> rpush score2 12 3 4 5 (integer) 5Copy the code
The values
Lrange key start end: obtain the value of the linked list elements from start to end. Start and end are counted from 0. It can also be negative, -1 for the element at the end of the list, -2 for the next-to-last, and so on…
example:
127.0.0.1:6379> lrange score1 0-1 1) "5" 2) "4" 3) "3" 4) "2" 5) "1" 3) "3" 4) "4" 5) "5"Copy the code
Delete value
Lpop Key: Returns and pops the first element in the linked list associated with the specified key, the header element. If the key does not exist, return nil; If key is present, the head element of the list is returned
example:
127.0.0.1:6379> lpop score1
"5"
127.0.0.1:6379> lpop score2
"1"
Copy the code
Rpop Key: Pops elements from the tail
example:
127.0.0.1:6379> rpop score1
"1"
127.0.0.1:6379> rpop score2
"5"
Copy the code
extension
Llen key: Returns the number of elements in the linked list associated with the specified key
example:
127.0.0.1:6379> llen score1
(integer) 3
127.0.0.1:6379> llen score2
(integer) 3
Copy the code
Lrem key count value: delete all elements whose value is value. If count is greater than 0, delete all elements whose value is value. If count is less than 0, delete all elements whose value is value. Delete all elements in the linked list equal to value.
example:
127.0.0.1:6379> Lrem score1 12 (integer) 1 127.0.0.1:6379> Lrem score2 12 (integer) 1Copy the code
Replace by index
Lset key Index value: Sets the value of the index element in the linked list. 0 represents the first element and -1 represents the last element. An exception is thrown if no pins exist for the operation linked list
example:
127.0.0.1:6379> lset score1 0 1
OK
127.0.0.1:6379> lset score2 0 1
OK
Copy the code
Inserts elements before/after the index
Linsert key before | after the pivot value: in the pivot element inserted before or after the value of this element
example:
127.0.0.1:6379> linsert score1 before 3 AAA (integer) 3 127.0.0.1:6379> lrange score1 0-1 1) "1" 2) "aaa" 3) "3" 127.0.0.1:6379> linsert score1 after 3 BBB (integer) 4 127.0.0.1:6379> lrange score1 0-1 1) "1" 2) "aaa" 3) "3" 4) "bbb"Copy the code
Rpoplpush Resource Destination: Pops up the tail element of the linked list and adds it to the header. [Loop operation]
example:
127.0.0.1:6379> lrange score1 0-1 1) "1" 2) "aaa" 3) "3" 127.0.0.1:6379> lrange score2 0-1 1) "BBB" 2) "1" 3) "4" 127.0.0.1:6379> rpoplpush score1 score2 "3" 127.0.0.1:6379> lrange score1 0-1 1) "1" 2) "aaa" 127.0.0.1:6379> lrange score2 0 -1 1) "3" 2) "bbb" 3) "1" 4) "4"Copy the code
4, Redis – set
The assignment
sadd key value[value1 value2…] : Adds elements to a set, not if the key already has a value
example:
127.0.0.1:6379> sadd ABC 12 3 4 (integer) 4Copy the code
srem key member[member1 member2…] : Deletes the member specified in set
example:
127.0.0.1:6379> srem abc 1 3
(integer) 2
Copy the code
The values
Smembers key: Gets all the members in a set
example:
127.0.0.1:6379> smembers abc
1) "2"
2) "4"
Copy the code
Sismember key member: Checks whether the specified member is in the set. 1 means it exists, 0 means it does not exist, or the key itself does not exist.
example:
127.0.0.1:6379> sismember abc 2
(integer) 1
127.0.0.1:6379> sismember abc 3
(integer) 0
Copy the code
Delete value
Set operations
Difference set operation
sdiff key1 key2… : Returns the members of key1 that differ from key2, depending on the order of the keys, i.e. the difference set
example:
127.0.0.1:6379> sadd set1 12 3 4 5 (integer) 5 127.0.0.1:6379> sadd set2 3 4 5 6 7 (integer) 5 127.0.0.1:6379> sdiff Set1 set2 1) "1" 2) "2" 127.0.0.1:6379> sdiff set2 set1 1) "6" 2) "7"Copy the code
Intersection operation
sinter key1 key2… : Return intersection
example:
127.0.0.1:6379> sinter set1 set2
1) "3"
2) "4"
3) "5"
Copy the code
And set operation
sunion key1 key2… : Returns the union
example:
127.0.0.1:6379 > sunion characters set2 1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7"Copy the code
The extension command
Scard key: Gets the number of members in the set
example:
127.0.0.1:6379> scard set1
(integer) 5
Copy the code
Srandmember Key: Returns a random member of the set
example:
127.0.0.1:6379> srandmember set1
"1"
127.0.0.1:6379> srandmember set1
"5"
127.0.0.1:6379> srandmember set1
"3"
Copy the code
sdiffstore destination key1 key2… Will: key1 key2… The offset members are stored at the destination
example:
127.0.0.1:6379> sdiffStore set3 set1 set2 (integer) 2 127.0.0.1:6379> smembers set3 1) "2"Copy the code
sinterstore destination key[key…] : stores the returned intersection at destination
example:
127.0.0.1:6379> sinterstore set4 set1 set2
(integer) 3
127.0.0.1:6379> smembers set4
1) "3"
2) "4"
3) "5"
Copy the code
5, Redis – sortedset
The assignment
zadd key score member score2 member2… : stores all members and their scores in a sorted-set. If the element already exists, the new fraction is used to replace the original fraction. The return value is the number of elements added to the collection, excluding pre-existing elements.
example:
127.0.0.1:6379> zadd list 50 xiaoming 100 xiaohong 200 xiaozhang
(integer) 3
Copy the code
The values
Zscore key member: Returns the score of a specified member
example:
127.0.0.1:6379> zscore list xiaohong
"100"
Copy the code
Zcard key: Gets the number of members in the collection
example:
127.0.0.1:6379> zcard list
(integer) 3
Copy the code
Range queries
Zrange key start end[withscores]: returns a member of the set with start-end, withscores
example:
127.0.0.1:6379> zrange list 0-1 withscores 1) "xiaoming" 2) "xiaohong" 3) "xiaozhang" 127.0.0.1:6379> zrange list 0-1 withscores 1) "xiaoming" 2) "50" 3) "xiaohong" 4) "100" 5) "xiaozhang" 6) "200"Copy the code
Zrevrange key start end[withscores]: Retrieves a member of the set with start-end. The parameter [withscores] indicates that the returned member contains its score.
example:
127.0.0.1:6379> zrevrange list 0-1 1) "xiaozhang" 2) "xiaohong" 3) "xiaoming" 127.0.0.1:6379> zrevrange list 0-1 withscores 1) "xiaozhang" 2) "200" 3) "xiaohong" 4) "100" 5) "xiaoming" 6) "50"Copy the code
Delete value
zrem key member[member…] : Removes a specified member from the collection. You can specify multiple members
example:
127.0.0.1:6379> zrem list xiaozhang
(integer) 1
Copy the code
Zremrangebyrank key start stop: deletes elements byrank range
example:
127.0.0.1:6379> zremrangebyrank list 0 1
(integer) 2
Copy the code
Zremrangebyscore key min Max: deletes elements according to the score range
example:
127.0.0.1:6379> zremrangebyscore list 50 120
(integer) 2
Copy the code
The extension command
Zrangebyscore key min Max [withscores][LIMIT offset count]: returns the members whose scores are in [min, Max] and sorts them byscore from lowest to highest. [withscores]: displays scores; [LIMIT offset count]:offset, starting from the element with offset and returning count members
example:
127.0.0.1:6379> zrangebyScore list 50 withscores limit 0 2 1) "xiaoming" 2) "50" 3) "xiaohong" 4) "100"Copy the code
Zincrby key Increment Member zincrby Key increment Member Zincrby Key increment Member Zincrby Key increment Member zincrby Key increment Member
example:
127.0.0.1:6379> zincrby list 30 xiaoming
"80"
Copy the code
Zcount key min Max: Gets the member whose score is between [min, Max]
example:
127.0.0.1:6379> zcount list 80 120
(integer) 2
Copy the code
Zrank key member: returns the rank of the member in the set (index from small to large).
example:
127.0.0.1:6379> zrank list xiaohong
(integer) 1
Copy the code
Zrevrank Key Member: Returns the rank of the member in the collection. (Index from largest to smallest)
example:
127.0.0.1:6379> zrevrank list xiaozhang
(integer) 0
Copy the code
6. General Redis command
Keys pattern: Retrieves all keys that match the pattern and returns all keys that match the key. * indicates any one or more characters
Wild card:
- * indicates zero or more characters
- ? Represents any character
Exits key: checks whether the key exists. 1 indicates that the key exists, and 0 indicates that the key does not exist
example:
127.0.0.1:6379> exists username
(integer) 1
127.0.0.1:6379> exists admin
(integer) 0
Copy the code
Rename Key newkey: Renames the current key
127.0.0.1:6379> rename username user
OK
127.0.0.1:6379> keys *
1) "list"
2) "abc"
3) "set1"
4) "information"
5) "set2"
6) "age"
7) "score2"
8) "set4"
9) "score1"
10) "set3"
11) "user"
Copy the code
Type key: Gets the value type of the specified key. This command is returned as a string. The returned strings are string, list, set, hash, and zset, or None if key does not exist
example:
127.0.0.1:6379> type user
string
127.0.0.1:6379> type list
zset
Copy the code
Expire key: Sets the expiration time, in seconds. If a key expires, Redis will delete it
example:
127.0.0.1:6379> expire ABC 10 (integer) 1 127.0.0.1:6379> keys * 1) "list" 2) "set1" 3) "information" 4) "set2" 5) "age" 6) "score2" 7) "set4" 8) "score1" 9) "set3" 10) "user"Copy the code
TTL key: obtains the remaining timeout period of the key. If the timeout period is not set, -1 is returned. If -2 is returned, the timeout does not exist.
example:
127.0.0.1:6379> expire user 10
(integer) 1
127.0.0.1:6379> ttl user
(integer) 3
127.0.0.1:6379> ttl user
(integer) -2
127.0.0.1:6379> keys *
1) "list"
2) "set1"
3) "information"
4) "set2"
5) "age"
6) "score2"
7) "set4"
8) "score1"
9) "set3"
127.0.0.1:6379> ttl information
(integer) -1
Copy the code
7. Other Redis features
Message subscription and publishing
We subscribe channel
example:
127.0.0.1:6379> subscribe mychat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "mychat"
3) (integer) 1
Copy the code
Psubscribe Channel *: bulk subscription channel
example:
127.0.0.1:6379> SUBSCRIBE s* Reading messages... (press Ctrl-C to quit) 1) "psubscribe" 2) "s*" 3) (integer) 1Copy the code
Publish Channel Content: Publishes messages in the specified channel
example:
127.0.0.1:6379> publish mychat 'today is a newday'
(integer) 1
Copy the code
Many database
Traditional databases such as MySQL databases can be created in their own terms, we can create database XXXX to create. Redis also has a database, but Redis has already created it in advance. There are sixteen databases in redis by default, 0,1,2…. 15. All data operations performed on radis are performed on database 0 by default, and key-value pairs cannot be shared between databases. We can think of the Redis database as a map collection.
Switching databases
Select database name: switch database
example:
127.0.0.1:6379> SELECT 1 OK 127.0.0.1:6379[1]> SELECT 15 OK 127.0.0.1:6379[15]> SELECT 16 (error) ERR DB index is out of rangeCopy the code
Database migration
Move NewKey Database name: Migrates the key of the current database to the specified database
example:
127.0.0.1:6379> keys *
1) "list"
2) "set1"
3) "information"
4) "set2"
5) "age"
6) "score2"
7) "set4"
8) "score1"
9) "set3"
127.0.0.1:6379> move information 1
(integer) 1
127.0.0.1:6379> keys *
1) "list"
2) "set1"
3) "set2"
4) "age"
5) "score2"
6) "set4"
7) "score1"
8) "set3"
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
1) "information"
Copy the code
Clearing the database
Flushdb Deletes all keys in the current database
Flushall Deletes all keys from all databases
Server command
Ping tests whether the connection is alive
example:
127.0.0.1:6379 > ping PONGCopy the code
Echo prints something on the command line
example:
127.0.0.1:6379 > echo hehe "hehe"Copy the code
Quit /Ctrl+C Exits the client
example:
127.0.0.1:6379 > quitCopy the code
Dbsize returns the number of keys in the current database
example:
127.0.0.1:6379 > dbsize (integer) 8Copy the code
Info Displays server information and statistics
example:
127.0.0.1:6379> info # Server redis_version:4.9.103 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:d727e4f6fe88cefd redis_mode:standalone ...... .Copy the code
8. Redis Persistence strategy
RDB strategy
RDB is the default persistence mechanism of Redis. It is equivalent to taking snapshots to save a state
Advantages:
- The snapshot speed is very fast and the data restoration speed is very fast
- Applicable to disaster backup
Disadvantages:
- Small memory machines are not suitable for use
If the RDB mechanism meets the requirements, snapshots will be taken (started at any time and anywhere), which will occupy certain system resources (suddenly) and may break down directly due to insufficient memory. (After the outage, the server will shut down, which is abnormal shutdown and data will be lost)
The RDB mechanism is suitable for computers with plenty of memory
When does the RDB take a snapshot?
- When the server is shut down, a snapshot is taken
- If the key meets certain conditions, a snapshot is taken
-
- Save 900 1# If at least one key changes every 900 seconds, the memory snapshot is dumped
- Save 300 10# Dump memory snapshot if at least 10 keys change every 300 seconds
- Save 60 10000# Dump memory snapshot if at least 10000 keys change every 60 seconds
AOF strategy
The AOF policy uses the log function to save data operations. By default, the AOF mechanism is disabled and only the statements that cause key changes are saved
Advantages:
- Use very little memory resources continuously
Disadvantages:
- Log files can be too large for disaster recovery
- The recovery efficiency is much lower than RDB
The AOF mechanism is suitable for computers with small memory
How does AOF back up data?
- Synchronization per second: AOF is performed once every second to save data, which has low security and saves system resources
- Each change synchronization: As long as there is a key change statement, the AOF saves data. It is relatively safe, but it wastes system resources and reduces efficiency
- Out of sync: There is no persistence. This configuration is not secure
AOF the configuration of the
- Always # Write to AOF files every second when data changes occur
- Everysec # synchronizes once per second, which is the default policy for AOF
- No # is never synchronized. Efficient but data is not persisted
Method to enable AOF mechanism
- Use :/aof to find the corresponding paragraph in the redis.config file
- Change appendOnly no to appendOnly yes
- Add appendfsync always to appendfsync