About Redis
Redis is an open source, a distributed NoSQL database system that uses the C language for "key/value" type data, characterized by high performance, persistent storage, and adapting to high concurrency scenarios. Redis is purely for the application, it is a high-performance Key-value database, and provides a variety of language APIs
The performance test results indicate that the set operation can be up to 110,000 times per second, and the get operation is 81,000 times/sec (of course different Server configuration performance differs).
Redis currently offers five types of data: string (String), list (linked list), hash (hash), set (set), and Zset (sorted set) (ordered set)
The comparison between Redis and memcached.
1.Memcached is multi-threaded, and Redis uses a single thread.
2.Memcached uses a pre-allocated memory pool to store data in a way that Redis uses on-site memory, and can configure virtual memory.
3.Redis can be persistent, master-slave replication, to achieve fault recovery.
4.Memcached is a simple key and value, but the Redis support data type is much more.
Redis storage is divided into memory storage, disk storage. From this point, it also shows that Redis and memcached are different. Redis is like memcached, where data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to disk or writes the modified operation to the appended record file, and Master-slave (Master-Slave) synchronization is implemented on this basis.
Redis has two storage methods, the default is the snapshot way, the implementation method is to periodically persist the memory snapshot (snapshot) to the hard disk, the disadvantage is that if the crash occurs after persistence, it will lose a piece of data. As a result of the perfectionist's push, the author added the AoF way. AoF that is append only mode, the Operation command is saved to the log file while writing the memory data, in a system with tens of thousands of concurrent changes, the command log is a very large amount of data, the management maintenance costs are very high, recovery rebuild time will be very long, which leads to the loss of AOF high-availability intention. What's more, Redis is a memory data structure model, and all of the advantages are based on the efficient atomic operation of complex memory structures, so that aof is a very uncoordinated part.
In fact, the main purpose of AOF is data reliability and high availability.
Redis Installation
Download Redis:https://github.com/dmajkic/redis/downloads
Copy the service program to a directory on a disk, such as:
File Description:
Redis-server.exe: Service Program
Redis-check-dump.exe: Local Database check
Redis-check-aof.exe: Update log check
Redis-benchmark.exe: Performance test to simulate the simultaneous sending of M-Sets/gets queries by n clients.
Redis-cli.exe: After the server is turned on, our clients can enter various commands to test
1. Open a CMD window and use the CD command to switch to the specified directory (F:\Redis) to run Redis-server.exe redis.conf
2. Reopen a CMD window, use the CD command to switch to the specified directory (F:\Redis) to run Redis-cli.exe-h 127.0.0.1-p 6379, where 127.0.0.1 is local ip,6379 is the default port on the Redis server (This enables a client program to test for special instructions).
You can set this service as a Windows system service, download the Redis service installation software, and install it. (https://github.com/rgl/redis/downloads)
Once the Redis service is installed, we will see it in the service of the computer
Then start the service.
Next, when using Redis, you need to download the C # driver (also known as the C # Development library), such as:
Redis Common data types
Using Redis, we don't have to focus on the problem of how to put an elephant into a refrigerator in the face of a monotonous database, but instead use Redis's flexible data structure and data manipulation to build different refrigerators for different elephants.
The most commonly used data types of Redis are the following five kinds:
String
Hash
List
Set
Sorted Set
String type
String is the most common type of data, and normal Key/value storage can be categorized as such. A key corresponding to a value,string type is binary safe. A Redis string can contain any data, such as a JPG image (which generates binary) or a serialized object. The basic operations are as follows:
[CSharp]View Plaincopy
- var client = New Redisclient ("127.0.0.1", 6379);
- Client. set<int> ("pwd", 1111);
- int pwd=client. get<int> ("pwd");
- Console.WriteLine (PWD);
- UserInfo UserInfo = new UserInfo () {UserName = "Zhangsan", userpwd = "1111"};<span style="font-family : the song body; >//</span> (Bottom layer using JSON serialization)
- Client. Set<userinfo> ("UserInfo", UserInfo);
- UserInfo user=client. Get<userinfo> ("UserInfo");
- Console.WriteLine (user. UserName);
- list<userinfo> list = new list<userinfo> () { new UserInfo () {username="Lisi", userpwd="111" },new UserInfo () {username="Wangwu", userpwd="123"}};
- Client. Set<list<userinfo>> ("list", list);
- List<userinfo>userinfolist=client. Get<list<userinfo>> ("List");
- foreach (UserInfo UserInfo in userinfolist)
- {
- Console.WriteLine (Userinfo.username);
- }
Hash type
Hash is a string-type field and value mapping table. Hash is particularly suitable for storing objects. Relative to Gencun each word of an object into a single string type. An object stored in a hash type consumes less memory and makes it easier to access the entire object.
As a key value exists, many developers naturally use the Set/get way to use Redis, in fact, this is not the most optimized way to use. In particular, in cases where VMs are not enabled, all Redis data needs to be put into memory, which is especially important for saving memory.
The overhead of serialization/deserialization is increased, and when one of the information needs to be modified, the entire object needs to be retrieved
Redis is a single-process single-threaded mode that uses queue mode to turn concurrent access into serial access. Redis itself does not have the concept of locking, and Redis has no competition for multiple client connections. Redis is a single-threaded program, why is it so fast?
1. Thread switching overhead caused by a large number of threads
2, Lock,
3, non-essential memory copy.
4. Redis's diverse data structures, each of which only does what it loves to do.
Hash corresponding to the value inside is actually a hashmap, there will be 2 different implementations, the HASHMAP members are relatively small, redis in order to save memory will be similar to a one-dimensional array of compact storage, without the use of real hashmap structure, When the number of members increases, it automatically turns into a real hashmap.
Key is still the user ID, value is a map, the map key is a member of the property name, value is the property value, so that the data can be modified and accessed directly through its internal map key (Redis called internal map key field), that is, through the Key (User ID) + field (attribute tag) can manipulate the corresponding attribute data, neither need to store data repeatedly, nor bring serialization and deserialization
[CSharp]View Plaincopy
- Client. Setentryinhash ("user", "UserInfo", "aaaaaaaaaa");
- list<string> list = client. Gethashkeys ("user");
- list<string> list = client. Gethashvalues ("UserInfo"); Get value
- list<string> list = client. Getallkeys (); //Get all the keys.
Redis provides a set of parameters for different data types to control memory usage, and the value inside of the Redis hash we mentioned earlier is a
HashMap, if the map has fewer members, a one-dimensional array will be used to store the map in a compact manner, eliminating the memory overhead of a large number of pointers, the following 2 items in the redis,conf configuration file.
Hash-max-zipmap-entries 64
Hash-max-zipmap-value 512.
The implication is that when value is not more than the number of members within the map is stored in a linear compact format, the default is 64, that is, the value of 64 members of the following is the use of linear compact storage, more than this value automatically into a real hashmap.
Hash-max-zipmap-value means that when value does not exceed the number of bytes per member within the map, linear compact storage is used to save space. The above two conditions any one condition above the set value will turn into the real hashmap, also will not save the memory again, this value sets how many need to weigh, the HashMap advantage is the discovery and the operation time is short.
A key can correspond to more than one field, and a field corresponds to a value
It is also important to note that Redis provides an interface (Hgetall) that can fetch all of the property data directly, but if the internal map has a large number of members, it involves traversing the entire internal map, which can be time-consuming due to the Redis single-threaded model. and other clients ' requests are completely unresponsive, which requires extra attention
We recommend using object categories and IDs to form key names, using fields to represent object properties, Word
Segment Values store property values, for example: Car:2 price 500
List type
List is a linked list structure, the main function is Push,pop, get all the values of a range, etc., the operation of key is understood as the list name. The Redis list type is actually a doubly linked list in which each child element is a string type. We can add delete elements from the head or tail of the list through the Push,pop operation, so that the list can be both a stack and a queue. The implementation of Redis list is a doubly linked list, which can support reverse lookup and traversal, but it is more convenient to operate, but it brings some additional memory overhead, and many implementations within Redis, including sending buffer queues, are also used in this data structure.
[CSharp]View Plaincopy
- Queue usage
- Client. Enqueueitemonlist ("name", "Zhangsan");
- Client. Enqueueitemonlist ("name", "Lisi");
- int count= client. GetListCount ("name");
- For (int i = 0; i < count; i++)
- {
- Console.WriteLine (client. Dequeueitemfromlist ("name"));
- }
- Stack use
- Client. Pushitemtolist ("name2", "Wangwu");
- Client. Pushitemtolist ("name2", "Maliu");
- int count = client. GetListCount ("name2");
- For (int i = 0; i < count; i++)
- {
- Console.WriteLine (client. Popitemfromlist ("name2"));
- }
Set type
It is an unordered collection of type string. Set is implemented by hash table, add, delete and find, we can take the set, intersection, Difference set.
[CSharp]View Plaincopy
- Working with Set types
- Client. Additemtoset ("A3", "ddd");
- Client. Additemtoset ("A3", "CCC");
- Client. Additemtoset ("A3", "tttt");
- Client. Additemtoset ("A3", "sssh");
- Client. Additemtoset ("A3", "HHHH");
- system.collections.generic.hashset<string>hashset=client. Getallitemsfromset ("A3");
- foreach (string str in hashset)
- {
- Console.WriteLine (str);
- }
- Seek and set
- Client. Additemtoset ("A3", "ddd");
- Client. Additemtoset ("A3", "CCC");
- Client. Additemtoset ("A3", "tttt");
- Client. Additemtoset ("A3", "sssh");
- Client. Additemtoset ("A3", "HHHH");
- Client. Additemtoset ("A4", "HHHH");
- Client. Additemtoset ("A4", "h777");
- system.collections.generic.hashset<string>hashset= Client. Getunionfromsets (new string[] { "A3","A4"});
- foreach (string str in hashset)
- {
- Console.WriteLine (str);
- }
- Ask for Intersection
- system.collections.generic.hashset<string> HashSet = client. Getintersectfromsets (new string[] {"A3", "A4"});
- Differential set.
- system.collections.generic.hashset<string> HashSet = client. Getdifferencesfromset ("A3",new string[] { "A4"});
Returns data that exists in the first collection, but does not exist in the other collection. Subtraction
Sorted set Type
Sorted set is an upgraded version of Set, which adds a sequential property to the set based on the addition of modifications. The element can be specified, and each time it is specified, Zset (representing an ordered collection) automatically re-adjusts the order of the new values. It can be understood as a table with columns, a column of value, and a list of stored orders. Key in operation is understood as the name of Zset.
The usage scenario for Redis sorted set is similar to set, except that the set is not automatically ordered, and the sorted set can be ordered by the user with an additional priority (score) parameter, and is inserted in an orderly, automatic sort. When you need a list of ordered and non-repeating collections, you can choose the sorted set data structure,
[CSharp]View Plaincopy
- Client. Additemtosortedset ("A5", "FFFF");
- Client. Additemtosortedset ("A5","bbbb");
- Client. Additemtosortedset ("A5", "GGGG");
- Client. Additemtosortedset ("A5", "CCCC");
- Client. Additemtosortedset ("A5", "waaa");
- system.collections.generic.list<string> List =client. Getallitemsfromsortedset ("A5");
- foreach (string str in list)
- {
- Console.WriteLine (str);
- }
Redis Tools and required information code full download, address: http://pan.baidu.com/s/1c0ChL5m
ASP. NET Redis development [GO]