Redis is an open source database that uses memory data structures for storage and can be used as a database, cache, and message broker. Redis supports rich data structures, such as: string (Strings), hash (),Hashslist (Lists), collection (),Setsordered collection (SortedSets). Redis has built-in replication, Lua scripting, transactions, and different levels of data hard disk persistence mechanisms, and provides a highly available Redis Sentinel and auto-partitioned clustering mechanism. is an effective means of building high-performance, scalable WEB applications.
- Installation configuration
- 1.1 Installation
- 1.2 Configuration
- 1.3 Starting the server
- 1.4 Starting the Client
- Data type
- 2.1 String (Strings)
- 2.2 Hash (Hashs)
- 2.3 List (Lists)
- 2.4 Set (Sets)
- 2.5 ordered set (SortedSets)
- Key operation
- Publish/Subscribe
- Transaction
- Connection Verification
1. Installation Configuration 1.1 Installation
Execute the following command in turn to download, unzip, compile, and install Redis:
$ wget http://download.redis.io/releases/redis-3.2.3.tar.gz
$ tar xzf redis-3.2.3.tar.gz
$ cd redis-3.2.3
$ make & make install
After installation, the/usr/local/binfollowing files are generated in the directory, as follows:
- redis-server: Redis Server-side startup program
- redis-cli: Redis Client Operations tool. You can also use Telnet to manipulate it based on its plain text protocol.
- redis-benchmark: Redis Performance Test Tool
- redis-check-aof: Data Repair Tool
- redis-check-dump: Check the Export tool
1.2 Configuration
The Redis configuration file is copied to the directory under the current directory/etc/:
$ CP redis.conf/etc/
To modify a configuration file:
$ vi/etc/redis.conf
Modifydaemonize yesthe parameters so that Redis can run in the background:
Daemonize Yes
1.3 Starting the server
To start Redis:
$/usr/local/bin/redis-server/etc/redis.conf
You can use thepscommand to view the boot situation:
$ PS-EF | grep Redis
If you see an output of the type below, it indicates a successful start:
Root 18443 1 0 13:05?
To enable Redis to run automatically, you also need to add it to the boot entry:
echo "/usr/local/bin/redis-server/etc/redis.conf" >>/etc/rc.local
For more information on Redis installation configuration, please refer to: Installing Redis under Linux CentOS
1.4 Starting the Client
redis-cliis a redis command-line client, and then we use this program to do one thing. Start this program:
$ redis-cli
Once started, the server can bePINGchecked for connectivity through commands:
127.0.0.1:6379> Pingpong
If you need to connect to a remote Redids server, you can specify it by addingredis-cliparameters.
The syntax structure is as follows:
$ redis-cli-h host-p port-a Password
For example, the host127.0.0.1,6379the remote server on the port, and add the authentication passwordpassword:
$ redis-cli-h 127.0.0.1-p 6379-a password127.0.0.1:6379> pingpong
2. Data type
Redis supports string (Strings), hash (Hashs), List (Lists), collection (Sets), ordered collection (SortedSets) 5 data types, this section describes the characteristics of these 5 data types and how to use them.
2.1 String (Strings)
Brief introduction
The string (Strings) is the most basic and most used data type. Redis strings are binary safe, which means that you can use Redis strings to store any type of data, such as JPEG pictures or serialized ruby objects.
A string type has a maximum length of.
You can use Redis's string types to do many useful things, such as:
- String types can be used as atomic counters and can be used in the following ways: INCR, DECR, Incrby
- Append content to a string using the Append command
- The GetRange and SetRange commands using strings can be used as a random access vector
- For a lot of data in very small space, or to create a Redis backup you can use the Getbit and Setbit commands
Using the example
Setting and taking values
UseSETa command to set a value of a string type, and multiple changes will causekeythe existing value to be modified.
UseGETkeyA value that can get a string that already exists:
redis> set mySite itbilu
OK
redis> set mySite itbilu.com
OK
redis> get mySite
"itbilu.com"
Self-increment, self-reduction
Not only can the string value be stored in the string type, it can also be accessed by integer value/floating-point value.
Redis providesINCR, andDECRso on, commands for integer values such as self-increment, decrement, and so on. Instead, itINCRBYFLOATcan be used to increment a specified floating-point value:
redis> set myInt 10
OK
redis> incr myInt
(integer) 11
redis> incrby myInt 2
(integer) 13
redis> decr myInt
(integer) 12
redis> decrby myInt 2
(integer) 10
redis> incrbyfloat myInt 1.2
"11.2"
Bulk operations
String types support bulk operations, are usedMSET,MSETNXcan be set in bulk for string typeskey-value, and areMSETNXonly set if they do not exist.
MGETCan be used to get multiple string types of values.
redis> mset domain itbilu.com name IT笔录
OK
redis> mget domain name
1) "itbilu.com"
2) "IT\xe7\xac\x94\xe5\xbd\x95"
For more information on string types, refer to: Redis string (String) type
2.2 Hash (Hashs)
Brief introduction
A Redis hash (Hashs) is a mapping between a string field and a string value, so it is well suited to represent an object type.
Hashing is a very useful storage method in some scenarios, and you can store millions of objects in a small Redis instance.
A Redis hash value can store232-1(4 billion) key-value pairs.
Using the example
Setting and taking values
Set the value of the hash typeHSETto use, take the valueHGETto get a single hash property value, or use theHGETALLget hash property and value:
redis> hset site domain itbilu.com
(integer) 1
redis> hget site domain
"itbilu.com"
redis> hgetall site
1) "domain"
2) "itbilu.com"
Bulk operations
Hashing also supports bulk operations. You can useHMSETto set multiple hash properties and values, usingHMGETget multiple hash properties and values:
redis> hmset site domain itbilu.com name IT笔录
OK
redis> hmget site domain name
1) "itbilu.com"
2) "IT\xe7\xac\x94\xe5\xbd\x95"
For more information on hash types, refer to: Redis hash type (hash)
2.3 List (Lists)
Brief introduction
The Redis list (Lists) is a simple list of strings and is sorted according to the insertion order.
You can use the Lpush method to insert a new element at the beginning of the list, or use the Rpush method to insert a new element at the end of the list. When an operation is performed on a null key, a new list is created. Similarly, if the list is emptied, the key is also removed from the key space.
A maximum of232-1(4 billion) elements can be stored in a redis list.
In terms of time complexity, the main feature of a Redis list is that when elements are added or removed at the beginning and end of a list, the access time is very fast. However, if you want to access the middle element of the list, it is relatively slow.
What we often do with lists is the following:
- For a timeline model on social networks, you can use Lpush to add new elements to the user timeline, and you can use Lrange to remove some recently inserted new elements.
- You can use Lpush and LTRIM to create a list that does not exceed the specified element, but only the nearest N elements.
- Lists can be delivered as raw messages, such as the Ruby Library resque the list structure as a background job.
- The list structure also supports a variety of operation commands, including blocking command Blpop.
Using the example
Setting and taking values
There are many ways to set a list type value. You canLPUSHeitherLRUSHinsert data by or to the beginning or end of the list, or you can manipulate the elements of theLSETspecified index bit in the list. Does notLSETallow operation on a list that does not exist.
List element values are used toLINDEXget the elements of the specified index bit in full use, or you can use the element that returns and removes theLPOPhead of the list, or use theRPOPelement that returns and removes the tail of the list.
redis> lpush mylist one
(integer) 1
redis> rpush mylist two
(integer) 2
redis> lset mylist 0 1
OK
redis> lindex mylist 0
"1"
redis> lpop mylist
"1"
redis> lindex mylist 0
"two"
2.4 Set (Sets)
Brief introduction
The Redis Collection (Sets) is an unordered collection of strings that are added, deleted, and tested for a member's timeO(1)(regardless of the number of elements, which is a constant time)
Duplicate member presence is not allowed in the collection. When an element is added more than once, its result is set to a single member multiple times. This allows us to manipulate elements directly without checking the presence of elements.
A Redis collection can contain a maximum of232-1(4 billion) elements.
The operations we can do with Redis collections are:
- With the uniqueness of the collection, all unique IP access can be assigned to a blog post. It is only necessary to use Sadd to add records each time a page is accessed to ensure the uniqueness of the IP.
- A Redis collection is a good representation of relationships. You can use Redis to create a tagging system and use collections to represent each label. For example, you can add the label ID of all objects to the collection to represent the specified label through the Sadd command, and you can use Sinter if you want each object to have 3 different people at the same time.
- by Spop or Srandmember commands, you can randomly extract the elements in the collection.
Using the example
Setting and taking values
The elements in the collection are unique, so we can add the same value to the collection more than once, inserting values into the collection using theSADDcommand.
Gets the elements in the collection using theSMEMBERScommand, or you can useSPOPget and delete a random value.
redis> sadd db MySQL MongoDB Redis
(integer) 3
redis> smembers db
1) "MySQL"
2) "MongoDB"
3) "Redis"
redis> spop db
"Redis"
redis> smembers db
1) "MySQL"
2) "MongoDB"
Operations between collections
Redis also provides methods for working with multiple collections, such as: You can get the difference between sets bySINTERquerying the intersection between collections, by getting the setSUNIONof sets between themSDIFF. The elements in the collection can beSMOVEmoved from one collection to another by command.
redis> sadd db MySQL MongoDB Redis
(integer) 1
redis> sadd sql MySQL MSSQL
(integer) 1
redis> sinter db sql
1) "MySQL"
redis> sunion db sql
1) "MySQL"
2) "MongoDB"
3) "Redis"
4) "MySql"
5) "MSSQL"
redis> sdiff db sql
1) "MongoDB"
2) "Redis"
redis> smove sql MSSQL db
(integer) 0
redis> smembers db
1) "MySQL"
2) "MongoDB"
3) "Redis"
2.5 Ordered set (SortedSets)
Brief introduction
The Redis ordered collection (SortedSets) is similar to a collection and is also a collection of string representations. The difference is that each element in an ordered collection is associated with score and is used for sorting the collection. adding, removing, and updating an ordered set is very fast because the elements are orderly. You can also get the range of elements very quickly through score or position.
Using the example
Setting and taking values
An ordered set is similar to a collection, and when you insert a value on an ordered collection, you specify ascoreparameter, which can be considered a weight or any ordinal number, in addition to the insertion element.
For an ordered collection, you can use theZADDset elements of the collection.
An ordered set does not provide a way to return all elements, either throughZRANGEthe collection of elements within a specified range, or by getting the rank of theZRANKspecified member, byZSCOREreturning the weight () value of the elementscore.
redis> zadd db 1 MySQL
(integer) 1
redis> zadd db 2 MongoDB 3 Redis
(integer) 2
redis> ZRANGE db 1 2
1) "MongoDB"
2) "Redis"
redis> ZRANK db Redis
(integer) 2
redis> ZSCORE db Redis
"3"
3. Key operation
In addition to data type operations, key operations are also basic and very important operations in Redis. Redis provides a number of key management related methods, such as:KEYSkey lookup,EXPIREATsetting the expiration time of keys, renamingRENAMEkeys, and so on.
Keys to find related actions
Before setting or adding a type element, it is generally necessary to first determine whether the specifiedkeyexists. To determine whether a key is saved using theEXISTS keycommand:
redis> exists dbs
(integer) 0
redis> exists db
(integer) 1
To prevent data type errors, you can use commands when you set a data value orkeymake a data type decision before inserting data into a typeTYPE key:
Redis> type Dbzset
Redis also provides a command for key management thatKEYScan be used to find keys in the database by matching the pattern:
redis> keys d*
1) "domain"
2) "db"
Validity
The expiration setting is very useful, and we can set a time-to-live for the specified key and automatically delete the key at expiration.
Set an expiration date, whichkeycan be used and set the validity period, which indicates the period of timeEXPIREby thePEXPIREnumber ofEXPIREseconds, and thePEXPIREvalidity period set by using millisecondskeyEXPIREATPEXPIREAT, andkeythe expiry time that can be used and set. They represent the expiry time by a Unix timestamp, which is akeysecond-level timestamp, which is a millisecond timestamp.
For keys that have the expiration date set, we can passTTLorPTTLview the key's expiration time, which is expressed in seconds, which is expressed as a number of milliseconds.
After you set the expiration time for a key, you can alsoPERSISTremove the expiration time from the command.
redis> set cache itbilu.com
OK
redis> expire cache 120
(integer) 1
redis> ttl cache
(integer) 114
redis> pttl cache
(integer) 110248
redis> persist cache
(integer) 0
redis> ttl cache
(integer) -1
Serialization of
To facilitate network transmission, we need to serialize the stored objects in the database or deserialize the received data. In Redis, you canDUMPserialize by specifying akeyvalue, and you can deserialize it by deserializing itRESTORE.
redis> set cache itbilu.com
OK
> dump cache
"\x00\nitbilu.com\x06\x00\xbf\xad\xf4\x86\xca\"\x90\xeb"
redis> restore cache-again 0 "\x00\nitbilu.com\x06\x00\xbf\xad\xf4\x86\xca\"\x90\xeb"
OK
redis> get cache-again
"itbilu.com"
Other operations
When you need to rename a key, you can use theRENAMEcommand. For keys that are no longer needed, you canDELdelete the period by command. Redis also supports transfers between databaseskey, which arekeytransferred through aMOVEnamed implementation.
redis> get cache-again
"itbilu.com"
redis> set cacha itbilu.com
OK
redis> rename cacha cahce
OK
redis> move cache 1
(integer) 1
redis> del cache
(integer) 0
4. Publish/Subscribe
Redis implements a similar messaging system through publish/subscribe (pub/sub), where the sender (the publisher) can send a message, and the recipient (user) can subscribe to the specified channel () tochannelreceive the message. Redis clients can subscribe to any number of channels.
Publish/Subscribe is a message communication pattern whose main purpose is to decouple the message Publisher from the Subscriber. Redis is a publish/subscribe server that enables message routing between message subscribers and publishers.
In Redis, the message type is done as a channel (channel). Subscribers can subscribe toSUBSCRIBEPSUBSCRIBEThe message type they want by or by command. WhenPUBLISHa publisher sends a specific type of message to a Redis server, the client who subscribes to the message receives the message. A client can be both a publisher and a subscriber to a message, or it can be one of those. A client can order multiple channels at the same time, or it can publish messages to multiple channels.
Using the example
Start a client (client1) and use theSUBSCRIBEnamed Subscriptionmsgevent:
redis> subscribe msg
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "msg"
3) (integer) 1
client2Use thePUBLISHcommand to send a message to the channel in another client ()msg:
redis> publish Msg "Hi, there" (integer) 1
client1You receive the following message:
1) "message"
2) "msg"
3) "hi, there"
5. Business
The Redis support transaction mechanism, a transaction in Redis is a set of commands that execute in a single step. The transaction has the following two properties:
- In a transaction, each command is a separate operation and is executed sequentially. During the execution of a transaction, the Redis server does not process requests from other clients.
- Redis transactions are atomic, and commands in one transaction either execute successfully or all do not execute.
RedisMULTImarks the start of a transaction through a command, and all subsequent commands entered are placed in a queue in order of precedence, and thenEXECexecuted atomically by command.
# Start a transaction
redis> MULTI
OK
# Here will enter some commands to be executed
redis> EXEC # Execute the previously entered commands one by one
For example, we can use Redis's transactions like this:
redis> multi
OK
redis> set domain itbilu.com
QUEUED
redis> get domain
QUEUED
redis> del domain
QUEUED
redis> exec
1) OK
2) "itbilu.com"
3) (integer) 1
6. Connection Verification
AUTH-Authentication
When connecting to a Redis server that requires authentication, you can specify the connection host, port, authentication password, and so on when you start the client. It can be validated by a command after the client startsAUTH.
For example, connect to a local Redis server and verify on the connection:
$ redis-cli
redis> set name "my name"
(error) NOAUTH Authentication required.
redis> auth 21jieyan2015
OK
redis> set name "my name"
OK
PING-Server Status detection
PINGThe command is used to detect the server state and will respond to a message if the server is running normallyPONG:
Redis> Pingpong
SELECT-Database Switchover
SELECTThe command is used to switch to the specified database. Databases in Redis are represented by the0starting index number, which defaults to0.
For example, switch to1the database with index number:
redis> set db_number 0
OK
redis> select 1
OK
redis[1]> get db_number
(nil)
redis[1]> select 0
OK
redis> get db_number
"0"
QUIT-Close Connection
Once the operation is complete, we can use theQUITcommand to request the server to close the connection to the current client. Once all pending replies (if any) are written successfully to the client, the connection is closed.
redis> quit$ # Connection disconnected
Transferred from: http://itbilu.com/database/redis/4JoBoVuKb.html
Redis database Getting Started Guide