C # Redis Use

Source: Internet
Author: User
Tags configuration settings download redis memcached redis server

Concept


Redis is an open source, using the ANSI C language, supporting the network, can be based on memory can also be persistent log-type, Key-value database, and memcached similar, it supports the storage of a relatively more value type, including string (string), list (linked list), Set (set), Zset (sorted set--ordered set), and hash (hash type). On this basis, Redis supports a variety of different ways of ordering. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to the disk or writes the modification operation to the appended record file, and on this basis, it realizes the Master-slave (master-slave) synchronization.

Redis supports master-slave synchronization. Data can be synchronized from the primary server to any number of servers, from which the server can be associated with other primary servers from the server. This enables Redis to perform a single layer tree replication. Saving can be intentionally or unintentionally to the data to write operations.
the difference between Redis and Memcached


Memcached are multiple threads, while Redis use a single thread. (Personally think memcached in the reading and writing processing speed due to Redis) Memcached uses a preconfigured pool of memory to store data in a way that uses onsite memory Redis, and can configure virtual memory. Redis can be persisted (that is, the Redis needs to always synchronize the data in memory to the hard disk to ensure persistence), master-slave replication, to achieve failure recovery. Memcached is simply key and value, but Redis support data types are more. Includes string (string), list (linked list), set (set), Zset (sorted set-ordered set), and hash (hash type).

Redis supports two ways of persistence:

(1): snapshotting (snapshot) is also the default method. (Make a backup of the data, save the data to a file)

(2) The way Append-only file (abbreviated AOF)

Snapshots are the default persistence method, which is to write in-memory data in a snapshot to a binary file with the default file name Dump.rdb. You can automate snapshot persistence through configuration settings. We can configure Redis to automatically take snapshots in n seconds if more than M key keys are modified.

AoF way: Because the snapshot mode is at a certain interval time, so if Redis accidentally down, you will lose the last snapshot after all the changes. AOF is more persistent than snapshot mode, is because when you use AOF, Redis appends each write command that you receive to a file, and then rebuilds the contents of the entire database in memory by executing the write command saved in the file when Redis restarts.
Windows installation Redis


to install the method in cmd :

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

2. Install package after downloading 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 testing to simulate the simultaneous dispatch of M-Sets/gets queries by n clients.
Redis-cli.exe: Once the server is open, our clients can enter various commands to test the

First as an administrator to open cmd (window +r), into the installation package download location. Input: Redis-server.exe redis.conf open Redis service. Prompt for a message without an error indicates a successful start.

This window will remain open if the Redis service is turned off. Use the client to test the data.

Now let's look at how Redis persisted in storing data to the hard disk. (The snapshot is the default persistence method, the default file name is Dump.rdb)

You can see that the Redis server saves the database on disk after 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 the. exe next next OK. After installation we will find the Redis service in the Windows service. Note Start the service after the related test.


Code Instances

You need to prepare three DLLs before invoking the Redis service. Download Address: "Redis call driver" can be referenced in the project.

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


static void Main (string[] args) {//Storage of 5 commonly used data types in Redis: string,hash,list,setsorted set Redisclient client = new Re
    Disclient ("172.21.0.192", 6379); Client.

    Flushall (); #region string Client.
    Add<string> ("Stringvaluetime", "I have 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 Method"); Console.WriteLine ("Data type: String. Key: StringValue, Value: {0}", client.

    Get<string> ("StringValue"));
    Student stud = new Student () {id = "1001", name = "Dick"}; 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", "John"); Client.
    Setentryinhash ("Hashid", "Age", "24"); Client.
    Setentryinhash ("Hashid", "Sex", "male"); Client.

    Setentryinhash ("Hashid", "Address", "Shanghai xx xx room"); 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 ();
    Gets all of the key.
    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 a range of all the values, etc., the operation of key is understood as the list name. * Redis's listA type is actually a two-way list of string types for each child element. We can add deletion elements from the head or tail of the list by Push,pop operation, * so that the list can be both a stack and a queue. Redis list is implemented as a two-way linked list, which can support reverse lookup and traversal, more convenient operation, but brings some additional memory overhead, * Many implementations within the Redis, including sending buffer queues are also used in this data structure * * client.  Enqueueitemonlist ("Queuelistid", "1 John"); Join the client.
    Enqueueitemonlist ("Queuelistid", "2. Zhang Si"); Client.
    Enqueueitemonlist ("Queuelistid", "3 Harry"); Client.
    Enqueueitemonlist ("Queuelistid", "4 Wang Maizi"); int q = client.
    GetListCount ("Queuelistid"); for (int i = 0; i < Q; i++) {Console.WriteLine ("Queuelistid out team value: {0}", client.   Dequeueitemfromlist ("Queuelistid")); Out team (advanced first out of queue)} client.  Pushitemtolist ("Stacklistid", "1 John"); into the stack client.
    Pushitemtolist ("Stacklistid", "2. Zhang Si"); Client.
    Pushitemtolist ("Stacklistid", "3 Harry"); Client.
    Pushitemtolist ("Stacklistid", "4 Wang Maizi"); int p = client.
    GetListCount ("Stacklistid"); for (int i = 0; i < P i++) {Console.WriteLine ("Stacklistid out Stack value: {0}", client. Popitemfromlist ("Stacklistid")); Out stack (advanced stack)} #endregion #region Set unordered set/* It is a string-type unordered collection. Set is implemented through hash table, add, delete and lookup, to set we can pick and set, intersection, Difference set * * client.
    Additemtoset ("Set1001", "Little 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 set valuea:{0}", item);//out of the result is not necessary} Clien
    T.additemtoset ("Set1002", "Little K"); Client.
    Additemtoset ("Set1002", "small C"); Client.
    Additemtoset ("Set1002", "Little a"); Client.
    Additemtoset ("Set1002", "Little J"); Hashset<string> HASTSETB = client.
    Getallitemsfromset ("Set1002"); foreach (string item in Hastsetb) {Console.WriteLine ("Set unordered set valueb:{0}", item);//out of the result is not necessary} HASHS Et<string> hashunion = client.
    Getunionfromsets (new string[] {"Set1001", "Set1002"}); foreach (String item in HashuniON) {Console.WriteLine ("Set1001 and Set1002: {0}", item);//and set} hashset<string> HASHG = client .
    Getintersectfromsets (new string[] {"Set1001", "Set1002"});  foreach (string item in HASHG) {Console.WriteLine ("Find the 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 other collections.  Difference Set] foreach (String item in Hashd) {Console.WriteLine ("Difference set for Set1001 and Set1002: {0}", item); Difference Set} #endregion #region setsorted ordered set/* sorted set is an upgraded version of Set, which adds a sequential attribute to the set, which is added to the modification. Yuan The time of the element can be specified, * after each designation, Zset (representing an ordered set) automatically adjusts the order of the new values. Can be understood as a table with columns, a list of stored value, a list of stored orders.
     The key in the operation is understood as Zset's name. * * 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 results:

Summary

The storage disaster of Redis is quite perfect, and the storage data types are all supported. The comparison pits are version 2. Server clusters are not supported under X, only stand-alone. The server cluster feature was unveiled in Redis 3.0.    The overall feeling of operation is relatively simple and easy to get started. Turn from: http://www.cnblogs.com/caokai520/p/4409712.html

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.