Operations for C # Redis

Source: Internet
Author: User

NuGet adds a reference to Stackexchange.redis

Because the Redis wrapper class uses Json at the same time, you need to add a json.net reference (Newtonsoft.json)

Redis Package Class

/// <summary>    ///Redis Operation class/// </summary>     Public classRedishelper {/// <summary>        ///Connection String/// </summary>        Private Static ReadOnly stringConnectionString = configurationmanager.connectionstrings["redisconnectionstring"].        ConnectionString; /// <summary>        ///Lock/// </summary>        Private ReadOnly Object_lock =New Object(); /// <summary>        ///Connection Object/// </summary>        Private volatileIconnectionmultiplexer _connection; /// <summary>        ///Database/// </summary>        Privateidatabase _db;  PublicRedishelper () {_connection=Connectionmultiplexer.connect (ConnectionString); _db=getdatabase (); }        /// <summary>        ///Get Connections/// </summary>        /// <returns></returns>        protectediconnectionmultiplexer getconnection () {if(_connection! =NULL&&_connection. isconnected) {return_connection; }            Lock(_lock) {if(_connection! =NULL&&_connection. isconnected) {return_connection; }                if(_connection! =NULL) {_connection.                Dispose (); } _connection=Connectionmultiplexer.connect (ConnectionString); }            return_connection; }        /// <summary>        ///Get Database/// </summary>        /// <param name= "db" ></param>        /// <returns></returns>         PublicIdatabase Getdatabase (int? db =NULL)        {            returnGetconnection (). Getdatabase (db??-1); }        /// <summary>        ///Set/// </summary>        /// <param name= "key" >Key</param>        /// <param name= "Data" >value</param>        /// <param name= "CacheTime" >Time</param>         Public Virtual voidSet (stringKeyObjectDataintcacheTime) {            if(Data = =NULL)            {                return; }            varEntrybytes =Serialize (data); varExpiresin =timespan.fromminutes (cacheTime); _db.        Stringset (Key, Entrybytes, Expiresin); }        /// <summary>        ///get values by key/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "key" ></param>        /// <returns></returns>         Public VirtualT get<t> (stringkey) {            varRValue =_db.            Stringget (key); if(!rvalue.hasvalue) {return default(T); }            varresult = Deserialize<t>(RValue); returnresult; }        /// <summary>        ///deserialization/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "Serializedobject" ></param>        /// <returns></returns>        protected VirtualT deserialize<t> (byte[] serializedobject) {            if(Serializedobject = =NULL)            {                return default(T); }            varJSON =Encoding.UTF8.GetString (Serializedobject); returnJsonconvert.deserializeobject<t>(JSON); }        /// <summary>        ///determine if you have set/// </summary>        /// <param name= "key" ></param>        /// <returns></returns>         Public Virtual BOOLIsSet (stringkey) {            return_db.        Keyexists (key); }        /// <summary>        ///Serialization of/// </summary>        /// <param name= "Data" ></param>        /// <returns>byte[]</returns>        Private byte[] Serialize (Objectdata) {            varJSON =jsonconvert.serializeobject (data); returnEncoding.UTF8.GetBytes (JSON); }    }
View Code

Console test Code

var " a " ; New Redishelper (). Set ("ABC"); Console.WriteLine ("OK"); Console.readkey ();

Run, view database

Get Value:

// var s = "a"; Console.WriteLine (new redishelper (). get<string> ("ABC")); // Console.WriteLine ("OK"); Console.readkey ();

Operations for 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.