C # Redis

Source: Internet
Author: User
Tags download redis redis server

Concept

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.

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.

The difference between Redis and Memcached
    • Memcached is multi-threaded, and Redis uses a single thread. (Personal opinion that memcached is in the speed of read and write processing due to Redis)
    • Memcached uses a pre-allocated pool of memory to store data in a way that Redis uses on-site memory, and can configure virtual memory.
    • Redis can be persisted (that is, Redis needs to constantly synchronize in-memory data to the hard disk to ensure persistence), master-slave replication, and fail-back.
    • Memcached is just a simple key and value, but the Redis support data type is much more. Includes string (string), list (linked list), set (set), Zset (sorted set-ordered set), and hash (hash type).

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.

Windows installation Redis

to install the Cmd method :

1. Download the installation package: Https://github.com/dmajkic/redis/downloads

2. After the installation package download, according to the operating system to select the corresponding version of the file, there will be several DLLs are:

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

First, open cmd as an Administrator (window +r) and go to the location where the installation package was downloaded. Input: Redis-server.exe redis.conf turn on Redis service. No error message indicates that the boot was successful.

This window remains turned on, and if the Redis service is turned off, it will be turned off. Test the data with the client.

Now let's see how Redis persists storage data to hard disk. (The snapshot is the default persistence mode, the default file name is Dump.rdb)

You can see that the Redis server is saving the database on disk for a period of time and the file is: Dump.rdb.

To install the Redis method with the Weindows service:

Download Redis Service installation package: Https://github.com/rgl/redis/downloads

After the download is complete, click on the. exe next next OK. After installation we will find the Redis service in the Windows service. Note that the test is in progress after starting the service.

Code instance

You need to prepare three DLLs before calling the Redis service. : "Redis Call driver" is referenced in the project.

Use Redis to store 5 commonly used data types: string,hash,list,setsorted Set Write instance code

static void Main (string[] args) {//store 5 commonly used data types in Redis: string,hash,list,setsorted set Redisclient client = new Redisc    Lient ("172.21.0.192", 6379); Client.    Flushall (); #region string Client.    Add<string> ("Stringvaluetime", "I've set the expiration time Oh 30 seconds will disappear", DateTime.Now.AddMilliseconds (30000)); while (true) {if (client. ContainsKey ("Stringvaluetime")) {Console.WriteLine ("String. Key: StringValue, Value: {0} {1}", client.            Get<string> ("Stringvaluetime"), DateTime.Now);        Thread.Sleep (10000);            } else {Console.WriteLine ("Key: StringValue, Value: I have 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 #region Hash Client.    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 List/* list is a linked list structure, the main function is Push,pop, get all the values of a range, etc., in Operation Key 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 a delete element from the head or tail of the list by Push,pop operationThe 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 extra memory overhead, * Many implementations within Redis, including sending buffer queues, are also used for 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"); int q = client.    GetListCount ("Queuelistid"); for (int i = 0; i < Q; i++) {Console.WriteLine ("Queuelistid Out of queue value: {0}", client.   Dequeueitemfromlist ("Queuelistid")); Outbound (queue FIFO)} 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"); int 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)} #endregion #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&LT ;string> hashunion = client.    Getunionfromsets (new string[] {"Set1001", "Set1002"}); foreach (string item in Hashunion) {Console.WriteLine ("Set1001 and Set1002 's set: {0}", item);//Set} HASHSET&LT ;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.  The difference set] foreach (String item in Hashd) {Console.WriteLine ("The difference between Set1001 and Set1002: {0}", item); Differential set} #endregion #region setsorted ordered set/* sorted set is an upgraded version of Set, which adds a sequential property to the set based on the addition of the modified. Element when you can refer to the Zset (representing an ordered collection) automatically re-adjusts the order of the new values after each designation. 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}

Output Result:

Summarize

Redis has a better storage tolerance, and the supported storage data types are more complete. The comparison pit is version 2. Server clusters are not supported under X, only stand-alone. The server clustering feature was unveiled in Redis 3.0. The overall feeling of operation is relatively simple and easy to get started.

Http://www.cnblogs.com/caokai520/p/4409712.html

C # Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.