Caching technology Redis use in C # and Redis encapsulation

Source: Internet
Author: User
Tags benchmark configuration settings object serialization redis serialization redis server value store
Redis is an open source, high-performance key-value store (Key-value store). It is often referred to as a data structure server (data structure server). Redis key values can include data types such as strings (strings), hashes (hashes), lists (lists), collections (sets), and ordered sets (sorted sets). For these data types, you can perform atomic operations. For example: Attaching to Strings (append), incrementing the values in the hash, adding elements to the list, calculating the intersection of the sets, and sets and sets of differences, and so on.

In order to achieve excellent performance, Redis employs an in-memory (in-memory) DataSet (DataSet). Depending on the usage scenario, you can dump the dataset to disk at intervals to persist the data, or append each operation command to the tail of the log.

Redis also supports master-slave replication (Master-slave replication), and has very fast non-blocking first-time synchronization (non-blocking A-synchronization), network disconnect, and so on. At the same time, Redis has other features, including simple check-and-set mechanisms, pub/sub, and configuration settings, so that Redis can behave more like caching (cache).

Redis also provides a rich client to support most of the popular programming languages at this stage. For a detailed support list, refer to Redis official documentation: Http://redis.io/clients. Redis itself is written using ANSI C and can run on most POSIX systems without external dependencies (external dependencies), such as Linux, *bsd, OS X, and Solaris.

Redis consists of four executables: Redis-benchmark, Redis-cli, Redis-server, redis-stat four files, plus a redis.conf form the final available package for the entire redis. Their role is as follows:

Daemon startup program for Redis-server:redis server
Redis-cli:redis Command line Operation tool. Of course, you can also use Telnet to operate on its plain text protocol.
Redis-benchmark:redis Performance Testing tool to test Redis performance in your system and your configuration
Redis-stat:redis State Detection Tool, can detect Redis current state parameters and delay status

Now you can start Redis, Redis has only one startup parameter, and that's his profile path.


First of all, you have to open redis-server, otherwise unable to connect services:


Open Redis-server:



you can then invoke the Redis attribute to store and retrieve the data:



Critical Code:

<span style= "color: #000000;"
>using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using Servicestack.redis;

Using ServiceStack.Redis.Support;
            Namespace Redisstudy {class Program {static void Main (string[] args) {try
                {//Get Redis operation interface Iredisclient Redis = Redismanager.getclient ();

                Hash table operation Hashoperator operators = new Hashoperator ();

                Remove a cached data bool IsTrue = Redis.remove ("Additemtolist");
                Add a list of strings to Redis list<string> storemembers = new list<string> () {"Han Meimei", "Li Lei", "Lucy"};
                Storemembers.foreach (x => redis.additemtolist ("Additemtolist", x));
                Gets the value set corresponding to the specified key Console.WriteLine ("The value set corresponding to the specified key:");
                var members = redis.getallitemsfromlist ("Additemtolist"); Members. ForEach (S => Console.WriteLine ("Additemtolist:" + s));

                Console.WriteLine ("");
                Gets the specified index location data Console.WriteLine ("Get the specified index location data:");
                var item = redis.getitemfromlist ("Additemtolist", 2);

                Console.WriteLine (item);

                Console.WriteLine ("");
                Storing data in a hash table ("Hash table data storage:") Console.WriteLine;
                UserInfo Userinfos = new UserInfo () {UserName = "Li lei", age = 45};    var ser = new Objectserializer ();
                Located in namespace ServiceStack.Redis.Support; BOOL results = operators. Set<byte[]> ("Userinfoshash", "Userinfos", Ser.
                Serialize (Userinfos)); byte[] Infos = operators.
                Get<byte[]> ("Userinfoshash", "Userinfos"); Userinfos = ser.
                Deserialize (infos) as UserInfo;

                Console.WriteLine ("Name=" + userinfos.username + "age=" + userinfos.age);

                Console.WriteLine ("");Object Serialization Storage Console.WriteLine ("Object serialization Mode Storage:");
                UserInfo uinfo = new UserInfo () {UserName = "john", age = 12}; BOOL result = redis.set<byte[]> ("Uinfo", Ser).
                Serialize (Uinfo)); UserInfo Userinfo2 = ser.
                Deserialize (redis.get<byte[]> ("Uinfo")) as UserInfo; Console.WriteLine ("Name=" + Userinfo2). UserName + "age=" + Userinfo2.

                Age);

                Console.WriteLine ("");
                Store value type Data Console.WriteLine ("Store Value type data:");
                Redis.set<int> ("My_age", 12);//or Redis.set ("My_age", 12);
                int age = redis.get<int> ("My_age");

                Console.WriteLine ("age=" + age);

                Console.WriteLine ("");
                Serializes the list data Console.WriteLine ("List data:");
                list<userinfo> userinfolist = new List<userinfo> {new userinfo{username= "Lucy", Age=1,id=1}, New UserinfO{username= "Mary", age=3,id=2},}; Redis.set<byte[]> ("Userinfolist_serialize", Ser.
                Serialize (userinfolist)); list<userinfo> userlist = ser.
                Deserialize (redis.get<byte[]> ("Userinfolist_serialize")) as list<userinfo>; Userlist.foreach (i => {Console.WriteLine ("Name=" + i.username + "age=" + i.age)
                ;
                });
                Free memory redis.dispose (); Operators.
                Dispose ();
            Console.readkey (); The catch (Exception ex) {Console.WriteLine (ex).
                Message.tostring ());
                Console.WriteLine ("Please open the Redis-server.exe");
            Console.readkey ();
 }}}}</span>

Redismanager class:

<span style= "color: #000000;"
>using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using Servicestack.redis; namespace Redisstudy {///<summary>///Redismanager class is primarily to create a link Pool Management object///</summary> public clas s Redismanager {///<summary>///Redis profile information///</summary> private stat
        IC String redispath = system.configuration.configurationsettings.appsettings["Redispath"];

        private static Pooledredisclientmanager _PRCM;
            <summary>///Static Construction method, initializing the link Pool Admin object///</summary> static Redismanager () {
        Createmanager (); ///<summary>///Create a link Pool Admin object///</summary> private static void Createmanage
        R () {_PRCM = Createmanager (new string[] {Redispath}, new string[] {redispath}); private static Pooledredisclientmanager CrEatemanager (string[] readwritehosts, string[] readonlyhosts) {//writeserverlist: writable Redis link address.
            Readserverlist: A readable redis link address.
            Maxwritepoolsize: Maximum number of write links.
            Maxreadpoolsize: Maximum number of Read links.
            AutoStart: Automatic reboot.
            Localcachetime: Local cache Expiration time, in seconds.
            Recordelog: Log is logged, which is used only to troubleshoot problems that occur when the Redis is running, such as Redis is working properly, please close the item. The Redisconfiginfo class is the record Redis connection information, which echoes//supports read/write separation in Redisconfig in the configuration file, balanced load return new POOLEDREDISCLI  Entmanager (Readwritehosts, readonlyhosts, new Redisclientmanagerconfig {maxwritepoolsize = 5,
        Write link pool link number maxreadpoolsize = 5,//Read link pool number AutoStart = true,}; private static ienumerable<string> splitstring (String strsource, String split) {R Eturn Strsource.split (Split.
        ToArray ()); ///<summary>///Client Cache Action Object///</summary> public static Iredisclient getclient () {if (_PRCM = = null) {
            Createmanager (); Return _PRCM.
        Getclient ();
 }}}</span>

Redisoperatorbase class:

<span style= "color: #000000;"
>using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using Servicestack.redis; namespace Redisstudy {///<summary>///Redisoperatorbase class, is the base class for Redis operations, inherits from the IDisposable interface, primarily for freeing memory///  T;/summary> public abstract class Redisoperatorbase:idisposable {protected iredisclient redis {get; Private set;
        private bool _disposed = false;
        Protected Redisoperatorbase () {Redis = Redismanager.getclient ();
                protected virtual void Dispose (bool disposing) {if (!this._disposed) {
                    if (disposing) {redis.dispose ();
                Redis = null;
        } this._disposed = true;
            public void Dispose () {Dispose (true); Gc.
        SuppressFinalize (this); }///<summary>///save data DB files to hard disk///</summary> public void Save () {Redis.save (); ///<summary>///asynchronously saves the data db file to the hard disk///</summary> public void Saveasync (
        ) {Redis.saveasync ();
 }}}</span>

Hashoperator class:

<span style= "color: #000000;"
>using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using Servicestack.text; namespace Redisstudy {///<summary>///Hashoperator class, is the Operation hash table class. Inherit from Redisoperatorbase class///</summary> public class Hashoperator:redisoperatorbase {public Hash Operator (): Base () {}///<summary>///determine if a data has been cached///</summary> public
        BOOL Exist<t> (string Hashid, string key) {return redis.hashcontainsentry (Hashid, key);  ///<summary>///store data to hash table///</summary> public bool Set<t> (string
            Hashid, string key, T t) {var value = jsonserializer.serializetostring<t> (t);
        Return Redis.setentryinhash (Hashid, key, value); ///<summary>///Removes a value from the hash///</summary> public bool Remove (StrinG Hashid, string key) {return Redis.removeentryfromhash (Hashid, key);
        ///<summary>///Removes the entire hash///</summary> public bool Remove (string key)
        {return redis.remove (key); ///<summary>///get data from hash table///</summary> public T get<t> (string has
            HId, String key) {String value = Redis.getvaluefromhash (Hashid, key);
        return jsonserializer.deserializefromstring<t> (value); }///<summary>///gets the entire hash of the data///</summary> public list<t> getall<
            T> (String Hashid) {var result = new list<t> ();
            var list = redis.gethashvalues (Hashid); if (list!= null && list. Count > 0) {list. ForEach (x => {var value = Jsonserializer.deseriAlizefromstring<t> (x); Result.
                ADD (value);
            });
        return result; ///<summary>///Set cache expiration///</summary> public void Setexpire (string key, Da
        Tetime datetime) {Redis.expireentryat (key, DateTime);
 }}}</span>

UserInfo class:

<span style= "color: #000000;" >using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Redisstudy
{
    [Serializable] public
    class UserInfo
    {public
        int Id;
        public string UserName;
        public int age;
    }
</span>


app.config configuration:

<?xml version= "1.0"?>
<configuration>
<startup><supportedruntime version= "v4.0" Sku= ". netframework,version=v4.0 "/></startup>
  <appSettings>
    <add key=" Redispath "value=" 127.0.0.1:6379 "/>
  </appSettings>
</configuration>







The above is the redis operation of the encapsulation class, directly to the call can be.

specific code Download:

Redis Code


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.