Redis Summary (ii) How Redis is used in C #

Source: Internet
Author: User

The previous article described the installation of Redis Redis Summary (a) Redis installation, as well as an overview of the advantages and application scenarios of Redis. This article focuses on explaining. How to use Redis and C # in net.

The Redis website offers many open-source C # clients. For example, Nhiredis, Servicestack.redis, Stackexchange.redis and so on. Among them, Servicestack.redis should be considered more popular. It provides a complete set of mechanisms for converting the object from Redis data structures to strongly typed objects and serializing the object json. So here we only introduce Servicestack.redis, which is also the client currently used in our products.

  Servicestack.redis address : Https://github.com/ServiceStack/ServiceStack.Redis

1. Create a console application and refer to the following Servicestack.redis related four class libraries. Or install the Redis common components Servicestack.redis through NuGet. Download the sample code.

2. Create a common class rediscachehelper for Redis operations,

Using system;using system.collections.generic;using system.configuration;using system.linq;using System.Text;using System.web;using servicestack.common.extensions;using servicestack.redis;using ServiceStack.Logging;namespace  weiz.redis.redistest{public class Rediscachehelper {private static readonly Pooledredisclientmanager pool =        Null        private static readonly string[] redishosts = null; public static int redismaxreadpool = Int.        Parse (configurationmanager.appsettings["Redis_max_read_pool"]); public static int redismaxwritepool = Int.        Parse (configurationmanager.appsettings["Redis_max_write_pool"]);             Static Rediscachehelper () {var redishoststr = configurationmanager.appsettings["Redis_server_session"]; if (!string.                IsNullOrEmpty (REDISHOSTSTR)) {redishosts = Redishoststr.split (', '); if (Redishosts.length > 0) {pool = new PooledredisclientmanaGer (Redishosts, redishosts, New Redisclientmanagerconfig () {                            Maxwritepoolsize = redismaxwritepool, maxreadpoolsize = Redismaxreadpool,                AutoStart = true}); }}} public static void Add<t> (string key, T value, DateTime expiry) {i            F (value = = null) {return;                } if (expiry <= datetime.now) {Remove (key);            Return The try {if (pool! = null) {using (var r = Pool).                            Getclient ()) {if (r! = null) {                            r.sendtimeout = 1000;                        R.set (key, value, Expiry-datetime.now);               }     }}} catch (Exception ex) {string msg = string. Format ("{0}:{1}" exception occurred!{            2} "," Cache "," Storage ", key); }} public static void Add<t> (string key, T value, TimeSpan slidingexpiration) {if            (value = = null)            {return;                } if (slidingexpiration.totalseconds <= 0) {Remove (key);            Return The try {if (pool! = null) {using (var r = Pool).                            Getclient ()) {if (r! = null) {                            r.sendtimeout = 1000;                        R.set (key, value, slidingexpiration); }}}} catch (Exception ex) {string ms g = String. Format ("{0}:{1}" exception occurred!{ 2} "," Cache "," Storage ", key); }} public static T get<t> (string key) {if (string.            IsNullOrEmpty (key)) {return default (T);            } T obj = default (t); try {if (pool! = null) {using (var r = Pool.                            Getclient ()) {if (r! = null) {                            r.sendtimeout = 1000;                        obj = r.get<t> (key); }}}} catch (Exception ex) {string ms g = String. Format ("{0}:{1}" exception occurred!{            2} "," Cache "," get ", key);        } return obj;                } public static void Remove (string key) {try {if (pool! = null) {using (var r = Pool.               Getclient ())     {if (r! = null) {r.sendtimeout = 1000;                        R.remove (key); }}}} catch (Exception ex) {string ms g = String. Format ("{0}:{1}" exception occurred!{            2} "," Cache "," delete ", key); }} public static bool Exists (string key) {try {if (Pool! = Nu ll) {using (var r = Pool.                            Getclient ()) {if (r! = null) {                            r.sendtimeout = 1000;                        return R.containskey (key); }}}} catch (Exception ex) {string ms g = String. Format ("{0}:{1}" exception occurred!{            2} "," Cache "," presence ", key); } return false;       }    }} 

Description: Rediscachehelper uses the client link pool mode, which should be the highest access efficiency. At the same time, it is more convenient to support read/write separation and load balancing.

3. Configuration files

    <!--Redis Start-to-    <add key= "sessionexpireminutes" value= ""/> <add key=    "Redis_ Server_session "value=" 127.0.0.1:6379 "/>    <add key=" Redis_max_read_pool "value=" 3 "/>    <add key=" Redis_max_write_pool "value=" 1 "/>    <!--redis end-->

 

4. Test program calls

Class program    {        static void Main (string[] args)        {            Console.WriteLine ("Redis Write cache: Zhong");            Rediscachehelper.add ("Zhong", "Zhongzhongzhong", DateTime.Now.AddDays (1));            Console.WriteLine ("Redis Get cache: Zhong");            String str3 = rediscachehelper.get<string> ("Zhong");            Console.WriteLine (STR3);            Console.WriteLine ("Redis Get cache: Nihao");            String str = rediscachehelper.get<string> ("Nihao");            Console.WriteLine (str);            Console.WriteLine ("Redis Get cache: Wei");            String str1 = rediscachehelper.get<string> ("Wei");            Console.WriteLine (str1);            Console.readkey ();        }    }

  

5. Output results

Redis Summary (ii) How Redis is used in C #

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.