This article mainly introduces about starting from zero Redis cache, has a certain reference value, now share to everyone, have the need for friends can refer to
About Redis
Redisis an open source useANSIClanguageWrite, support network, log type that can be persisted based on memory,Key-valueDatabase, and is available in multiple languagesAPI. From .years3Month thefrom the day,Redisthe development work byVMwarehost. From -years5month begins,Redisthe development byPivotalsponsorship.
Redisis aKey-valueStorage System. and theMemcachedSimilarly, it supports the storage ofvaluetypes are relatively more, includingString (string),List (Linked list),Set (Collection),Zset (sorted set--ordered Collection)and theHash(hash type). TheseData Typeall supportPush/pop,Add/removeand take the intersection of the set and the difference set and richer operations, and these operations are atomic. On this basis,Redissupports sorting in a variety of different ways. With thememcached, the data is cached in memory in order to ensure efficiency. The difference isRedisperiodically writes the updated data to the disk or writes the modification to the appended record file, and on this basis implements theMaster-slave (Master)synchronization.
Redisis a high-performanceKey-valuedatabase. RedisTo a large extent compensatedmemcachedThis type ofKey/valueThe lack of storage, in the DepartmentSub-occasions can be a good complement to the relational database. It provides aJava,C + +,C #,PHP,JavaScript,Perl,object-c,Python,Ruby,Erlangand other clients, the use is very convenient. [1]
Redis supports master-slave synchronization. Data can be synchronized from the primary server to any number of slave servers, from the server to the primary server that is associated with other slave servers. This enables Redis to perform single-layer tree replication. You can write to the data intentionally or unintentionally. Because of the full implementation of the Publish / subscribe mechanism, you can subscribe to a channel and receive a complete message release record from the master server when the tree is synchronized anywhere from the database. Synchronization is helpful for the scalability and data redundancy of read operations.
Redis The official website address, very good remember, is Redis.io . (specifically checked, the domain name suffix io belongs to the national domain name, is British Indian Ocean Territory, namely British Indian Ocean Territory)
Currently, Vmware in funding the Redis development and maintenance of the project.
2. Installation of Redis
Unzip the installation file
After the decompression
Perform make to compile
Compile OK,
Enter SRC directory
REDIS-CLI Terminal operation
Redis-server starting a Redis service file
Redis-benchmark pressure test File
REDIS-CHECK-XX Inspection Vehicle backup File script
Create a Redis run directory and copy two running files past
Copy config file past
3. Start the Redis service
Front-end boot Redis service Success Flag
./redis-server
At this point, there is a problem, the current start is not closed, a close will be gone, so need to modify
Stop Service CTRL + Z
Stop the Redis service first
Use the background to start the Redis service
Vim redis.conf
Change to Yes to save, set background to start Redis
Start again
Discovery or front-end startup
Start with a configuration file to start with
View the next Redis process
Discover that Redis is up
4. Simple to use
Three variables are set, all three of which are stored in memory
How to read?
get!
5. Specific operation
1. Operation of Key
In Redis, out of the "\ n" and the space can not be the name of the composition of the content, the other content can be used as the name of the key part, the name length does not require
In other words, it's the variable name.
Code |
Role |
Exists Key |
Whether there is |
Del key1 Key2 .... |
Deletes the specified key |
Type Key |
Returns the value type of the given key |
Key pattern |
Returns all keys that match the specified pattern |
Rename Oldkey Newkey |
Change the name |
Dbsize |
Returns the number of keys for the current database |
Expire Key seconds |
Specify an expiration time for key |
Ttl Key |
Returns the number of seconds expired for key |
Select Db-index |
Select Database |
Move Key Db-index |
Move key from the current database to the specified database |
Flushdb |
Delete all keys in the current database |
Flushall |
Remove all keys from all databases |
Here are examples of the use of one
2. Operation of type String
String is the most basic type of Redis
A Redis string can contain any data, including JPG images or serialized objects
Maximum limit for a single value value is 1G bytes
Code |
Role |
Set Key value |
Sets the value of the key corresponding to string type |
Mset Key1 Value1...keyn Valuen |
Set values for multiple keys at once |
Mget key1 Key2 ... KeyN |
Get the value of multiple keys at once |
INCR Key |
Do + + operations on the value of key |
DECR key |
Ibid.-Operation |
Incrby Key Integer |
Same INCR plus specified value |
Decrby Key Integer |
Same DECR minus specified value |
Append Key value |
Append value to the string of the specified key |
Substr Key Start end |
Returns the string value of the truncated key |
3. Introduction and use of List linked list types
The list type is actually a doubly linked list
If you want to query the top 10 most recent users,
To check each other, too much consumption of resources
List Chain Representation example diagram:
Save the latest 5 user information from the login system via list lists
The new user comes in and the old user kicks out
How does the list work?
Code |
Role |
Lpush Key string |
Adds a string element to the head of the list in key |
Rpop Key |
Deletes an element from the tail of the list and returns the element to delete |
Lien Key Returns key |
The length of the corresponding list, the key value does not exist return 0, if the key corresponding type is not a list return error |
Rpush Key string |
Ibid., add at tail |
Lpop Key |
Removes the element from the head of the list and returns the deleted element |
Ltrim Key Start end |
Intercept list, preserving elements within a specified range |
4. Set Collection type
Redis's set is an unordered collection of type string.
The set element can contain a maximum of (2 of 32 square-1) elements
Individual elements in each collection cannot be duplicated
Code |
Role |
Sadd Key Member |
Adds a string element to the set set of key corresponding to return success 1 |
Srem Key Member |
Removed the given element from key corresponding set, successfully returned 1 |
Smove P1 P2 Member |
Remove the member from the P1 corresponding set and add it to the P2 corresponding set |
SCard Key |
Returns the number of elements of a set |
Sismember Key Member |
Determine if member exists in set |
Sinter key1 Key2 .... |
Returns the intersection of all given keys |
Sunion Key1 Key2 |
Returns the set of all the given keys |
Sdiff Key1 Key2. |
Returns the difference set for all given keys |
Smembers Key |
Returns the key corresponding to all the elements of the set, the result is unordered |
There's a key five elements inside.
And then add a linken
5. Sortset Sort Collection type operations
Like set, sorted set is also a collection of string elements
The difference is that each element will be associated with a right
The elements in the collection can be obtained in an orderly manner by weight values
Case:
Get the hottest Top 5 posts learning with sort set implementation
Each element in the sorted collection is a value, a combination of weights
Code |
Role |
Zadd Key Score Member |
Adds an element to the collection, the element exists in the collection, and updates the corresponding score |
Zrem Key Member |
Delete the specified element, 1 succeeded, 0 does not exist |
Zincrby Key INCR Member |
Increase the score value of the corresponding member according to the INCR amplitude and return the score value |
Zrank Key Member |
Returns the rank (subscript) of the specified element in the collection, where the element is an score from small to large |
Zrange Key Start end |
An element similar to the Irange operation from the specified interval in the collection, returning an ordered result |
Zrevrange Key Start end |
Ibid., return is in reverse order |
Zcard Key |
Returns the number of elements in the collection |
Zscore Key Elemet |
Returns the score corresponding to the given element |
Zremrangebyrank Key min Max |
Delete the element in the collection that is ranked in the given point range |
6. Snapshot persistence
900 seconds a key change on (snapshot) Save
300 SEC 10 Key Change (snapshot) Save
10,000 key changes in a minute (snapshot) Save
The benefits of such control:
The frequency of data modification is very high, the frequency of backup is also high,
The frequency of data modification is low and the frequency of backup is low.
The name of the snapshot persistence save
Manually initiating snapshot persistence
If you are on this machine:
7. AoF Persistence
Essence: The user executes each "write" command (add, delete, modify) back to the file, restore the time to perform specific "write" instructions
Open AOF Persistence clears Redis internal data
Turn on aof persistence
Configuration file is modified restart service
View Redis process: Ps–a | grep Redis
-9 forced Kill process
Start a new process
AOF Append Persistent Backup frequency
Always force write to disk every time you receive a write instruction, it is slow, but it can maintain full persistence
Everysec is forced to write to disk once per second, a good compromise in performance and persistence, recommended
No full reliance on OS performance is best, persistence is not guaranteed
8. master-Slave mode
To reduce the load on each Redis server, you can set up a few and master-slave mode
A server payload "write"
Other server load "read"
The primary server is automatically synchronized to the slave server
Modify IP address and port number