Installation and use of Redis
In the previous three articles about MONGODB database development use, strictly speaking this can not be categorized in MongoDB database development, but Redis has a very close relationship with MongoDB database, they are very close, Redis is mainly in-memory NoSQL database, Used to raise high performance; MongoDB database is a NoSQL database in a file, used for data serial number storage, and they are closely related and different. This article mainly introduces the installation and use of Redis, laying the groundwork for the joint use of the Redis and MongoDB databases behind.
1. Redis Foundation and Installation
Redis is an open source, write with ANSI C language, support network, memory-based and persistent, Key-value database, and memcached similar, it supports storage of the value type is relatively more, including string (string), list (linked list), Set (set), Zset (sorted set--ordered set), and hash (hash type). Based on this, Redis supports sorting in a variety of different ways. As with memcached, 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.
The Redis code follows ANSI-C and can be installed on all POSIX systems (such as Linux, *BSD, Mac OS X, Solaris, etc.). And Redis does not rely on any nonstandard libraries, and no compilation parameters are required to be added.
1) Redis supports two persistence modes:
(1): snapshotting (snapshot) is also the default mode. (Make a backup of the data, save the data to a file)
(2) How to Append-only file (abbreviated AOF)
Snapshots are the default persistence method by which the in-memory data is written to a binary file in a snapshot, with the default file name Dump.rdb. You can automatically make snapshot persistence by configuring settings. We can configure Redis to take snapshots automatically if more than M key keys are modified within n seconds.
AOF mode: Because the snapshot mode is done at a certain interval, if Redis accidentally down, it will lose all the changes after the last snapshot. AOF is more persistent than snapshot, because Redis appends each received write command to a file by using the Write function, and when Redis restarts, it rebuilds the contents of the entire database in memory by re-executing the Write command saved in the file.
2) REDIS data structure
The Redis author, Antirez, once called it a data structure server (datastructures Server), which is a very accurate statement that all of Redis's functions are to store data in several of its inherent structures, and provide the interface to the user to manipulate these kinds of structures. We can imagine those intrinsic data types and their operations in various languages.
Redis currently offers four types of data:string,list,set and zset(sorted set) and Hash.
- string is the simplest type, you can understand it as a type with memcached, a key corresponds to a value, and the operation supported on it is similar to the operation of Memcached. But it's more versatile.
- List is a linked list structure, the main function is push, pop, get all the values of a range and so on. Key in operation is understood as the name of the linked list.
- set is a set, and we are similar to the concept of the set in mathematics, the operation of the set has added delete elements, there are multiple sets of orthogonal and poor operation. In Operation Key is understood as the name of the collection.
- Zset is an upgraded version of set, and he adds a sequential attribute on the set, which can be specified when adding a modified element, and Zset automatically re-adjusts the order of the new values after each assignment. It can be understood that there are two columns of MySQL table, one column of value, and one in the order of storage. Key in operation is understood as the name of Zset.
- The hash data type allows users to use Redis to store object types, and one important advantage of the hash data type is that when you store data objects with very few key values, the memory consumption of the data store is small. For more information on Hash data types, see:/http Code.google.com/p/redis/wiki/hashes
3) Redis data storage
The Redis storage is divided into memory storage, disk storage, and log files, which are configured with three parameters in the configuration file.
Save seconds Updates,save Configuration, indicates how many times the update operation has been synchronized to the data file. This can be a combination of multiple conditions, such as the default configuration file settings, set three conditions.
appendonly Yes/no ,appendonly configuration, indicates whether logging occurs after each update operation and, if not turned on, may result in data loss over a period of time when power is lost. Because the Redis itself synchronizes data files in sync with the save conditions above, some data will only exist in memory for a period of time.
Appendfsync no/always/everysec ,appendfsync configuration,no indicates that the data cache of the operating system is synchronized to disk, always means to manually call Fsync() to write data to disk after each update operation,everysec to synchronize once per second.
4) Installation of Redis
Redis can be run on different platforms, but I'm primarily based on windows, so the following are mainly based on the Windows platform.
Redis can be installed as a DOS window boot, or can be installed as a Windows service, generally for convenience, we prefer to install it as a Windows service, which can be more convenient to manage. : https://github.com/MSOpenTech/redis/releases download, install as a Windows service.
Currently available for download to the latest version of Windows 3.0, after installation as a Windows service, you can see the Redis service running in the system after installation, as shown in.
After installing Redis, there is also a Redis companion Redis Desktop Manager that needs to be installed so that you can see in real time what data is in the Redis cache, with the following address: Http://redisdesktop.com/download
Download the version that belongs to your platform
After downloading the installation, open the runtime interface, if we add the data of the key value inside, then we can see the data inside.
2. Use of Redis in C #
Redis currently offers four types of data:string,list,set and zset(sorted set) and Hash. So it has a corresponding encapsulation in C #, and there are a lot of people who have encapsulated him, providing a lot of response to the development package, specifically accessible to http://redis.io/clients#c for understanding. Generally recommended with Servicestack.redis package driver is better, the specific use can refer to Https://github.com/ServiceStack/ServiceStack.Redis.
When we develop C # code, we can add the corresponding Servicestack.redis reference on top of the NuGet package, as shown below.
In the pop-up NuGet package, enter Servicestack.redis to search and add the following driver references.
This adds several corresponding assemblies in the project reference, as shown below.
Using Redis in C #, you first need to instantiate a Redis client class, as shown below.
Create a Redis client class Redisclient clients = new Redisclient ("127.0.0.1", 6379);
Before using, we need to clear all the key-value stores, using the Fushall method, as shown below
The Redis flushall command empties the data for the entire REDIS server (all keys for all databases are deleted). client. Flushall ();
According to the above driver, you can write some demo code for different types of processing, the following code is an excerpt from the case on the Internet to introduce.
#region A string type of test code client. Add<string> ("Stringvaluetime", "string with Expiration", DateTime.Now.AddMilliseconds (10000)); while (true) {if (client. ContainsKey ("Stringvaluetime")) {Console.WriteLine ("String. Key: StringValue, Value: {0} {1}", C Lient. Get<string> ("Stringvaluetime"), DateTime.Now); Thread.Sleep (10000); } else {Console.WriteLine ("Key: StringValue, Value: expired {0}", DateTime.Now); Break }} client. Add<string> ("StringValue", "string and memcached operation methods"); Console.WriteLine ("Data type: String. Key: StringValue, Value: {0}", client. Get<string> ("StringValue")); Student stud = new Student () {id = "1001", name = "John Doe"}; Client. Add<student> ("stringentity", stud); Student Get_stud = client. Get<student> ("StringentitY "); Console.WriteLine ("Data type: String. Key: Stringentity, Value: {0} {1}", Get_stud.id, Get_stud.name); #endregion the test code client #region the hash type. Setentryinhash ("Hashid", "Name", "Zhang San"); Client. Setentryinhash ("Hashid", "Age", "24"); Client. Setentryinhash ("Hashid", "Sex", "male"); Client. Setentryinhash ("Hashid", "Address", "xx room xx, Shanghai"); List<string> Haskkey = client. Gethashkeys ("Hashid"); foreach (string key in Haskkey) {Console.WriteLine ("Hashid--key:{0}", key); } list<string> haskvalue = client. Gethashvalues ("Hashid"); foreach (string value in Haskvalue) {Console.WriteLine ("Hashid--value:{0}", value); } list<string> allkey = client. Getallkeys (); Get all the keys. foreach (string key in Allkey) {Console.WriteLine ("Allkey--key:{0}", Key); } #endregion #region The test code for the list type */* list is a linked list structure, the main function is Push,pop, get all the values of a range, etc. The key in the work is understood as the list name. * The Redis list type is actually a doubly linked list where 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 the Redis list is a doubly linked list, which can support reverse lookup and traversal, but it is more convenient to operate, but it introduces some additional memory overhead, * Many implementations within Redis, including sending buffer queues, are also used in this data structure */ Client. Enqueueitemonlist ("Queuelistid", "1. Zhang San"); The queue client. Enqueueitemonlist ("Queuelistid", "2. Zhang four"); Client. Enqueueitemonlist ("Queuelistid", "3. Harry"); Client. Enqueueitemonlist ("Queuelistid", "4. Pock"); Long q = client. GetListCount ("Queuelistid"); Console.WriteLine (client. Getitemfromlist ("Queuelistid", 0)); for (int i = 0; i < Q; i++) {Console.WriteLine ("Queuelistid Out of queue value: {0}", client. Dequeueitemfromlist ("Queuelistid")); Outbound (queue FIFO)} q = client. GetListCount ("Queuelistid"); CoNsole. WriteLine (q); Client. Pushitemtolist ("Stacklistid", "1. Zhang San"); into the stack client. Pushitemtolist ("Stacklistid", "2. Zhang four"); Client. Pushitemtolist ("Stacklistid", "3. Harry"); Client. Pushitemtolist ("Stacklistid", "4. Pock"); Long p = client. GetListCount ("Stacklistid"); for (int i = 0; i < P; i++) {Console.WriteLine ("Stacklistid out Stack value: {0}", client. Popitemfromlist ("Stacklistid")); Out stack (stack advanced)} q = client. GetListCount ("Stacklistid"); Console.WriteLine (q); #endregion the test code for #region set unordered collection/* 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 */client. Additemtoset ("Set1001", "small a"); Client. Additemtoset ("Set1001", "small B"); Client. Additemtoset ("Set1001", "small C"); Client. Additemtoset ("Set1001", "small d"); Hashset<string> Hastseta = client. Getallitemsfromset ("Set1001 "); foreach (string item in Hastseta) {Console.WriteLine ("Set unordered collection Valuea:{0}", item);//The result is not required } client. Additemtoset ("Set1002", "small k"); Client. Additemtoset ("Set1002", "small C"); Client. Additemtoset ("Set1002", "small a"); Client. Additemtoset ("Set1002", "Little J"); Hashset<string> HASTSETB = client. Getallitemsfromset ("Set1002"); foreach (string item in Hastsetb) {Console.WriteLine ("Set unordered collection Valueb:{0}", item);//The result is not required } hashset<string> hashunion = client. Getunionfromsets (new string[] {"Set1001", "Set1002"}); foreach (string item in Hashunion) {Console.WriteLine ("Set1001 and Set1002 's set: {0}", item);//Set } hashset<string> HASHG = client. Getintersectfromsets (new string[] {"Set1001", "Set1002"}); foreach (string item in HASHG) { Console.WriteLine ("Intersection of Set1001 and Set1002: {0}", item); Intersection} hashset<string> hashd = client. Getdifferencesfromset ("Set1001", new string[] {"Set1002"}); [returns data that exists in the first collection but does not exist in the other collection. Difference Set] foreach (String item in Hashd) {Console.WriteLine ("Differential set for Set1001 and Set1002: {0}", ite m); Differential set} #endregion the test code for the ordered set of #region setsorted/* Sorted set is set An upgraded version, which adds a sequential attribute to the set based on the addition of the modified. Element can be specified, * Once specified, Zset (indicates 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. */client. Additemtosortedset ("SetSorted1001", "1. Liu Chai"); Client. Additemtosortedset ("SetSorted1001", "2. Star"); Client. Additemtosortedset ("SetSorted1001", "3. Piglets"); List<string> listsetsorted = client. Getallitemsfromsortedset ("SetSorted1001"); foreach (string item in listsetsorted) {Console.WriteLine ("SEtsorted ordered set {0} ", item); } #endregion
For a specific type of class object, you can also use the As method to convert to the corresponding processing object for processing, as shown below
Iredistypedclient<phone> phones = client. As<phone> ();
The specific test code is shown below.
<summary>///Redis processing examples for object classes///</summary> private void Btntypevalue_click (o Bject sender, EventArgs e) {iredistypedclient<phone> phones = client. As<phone> (); Phone phonefive = phones. GetValue ("5"); if (phonefive = = null) {Thread.Sleep (50); phonefive = new Phone {Id = 5, Manufacturer = "Apple", Model = "xxxxx", Owner = new Person {Id = 1, Age = +, Name = "Wu Huacong", profession = "Computer", Surname = "Wuhuacong"}; Phones. Setentry (PhoneFive.Id.ToString (), phonefive); } client. Store<phone> (new Phone {Id = 2, Manufacturer = "LG", Model = "Test-xxx", Owner = new person {Id = 2, age = +, Name = "Test", profession = "Teacher", Surname = "Wuhuacong"} }); var message = "Phone model is" + Phonefive.manufacturer + ","; Message + = "Phone Owner Name is:" + phoneFive.Owner.Name; Console.WriteLine (message); }
The above is the installation of Redis and simple examples of the use of instructions, in particular, we can take advantage of Redis's high-performance features to build our cache data, and can take advantage of the Redis and MongoDB database perfect convergence, can be integrated together to do better, For the relevant background to provide more efficient data processing operations, after all, in the context of the Internet, performance is very important.
Installation and use of Redis