Redis Summary (ii) How to Use redis in C,

Source: Internet
Author: User

Redis Summary (ii) How to Use redis in C,

In the previous article, we talked about installing redis "Redis Summary (1) Redis installation", and also introduced the advantages and application scenarios of redis. This article focuses on how to use redis and C # In. NET #.

 

The official Redis website provides many open-source C # clients. For example, Nhiredis, ServiceStack. Redis, and StackExchange. Redis. Among them, ServiceStack. Redis should be popular. It provides a complete set of mechanisms for converting strong type objects from Redis data structures and serializing the object json. So here we will 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 reference the following four libraries related to ServiceStack. Redis. Or install ServiceStack. Redis, a common component of Redis, through Nuget. Download the sample code.

 

2. Create a public 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 s Tatic int RedisMaxReadPool = int. parse (ConfigurationManager. appSettings ["redis_max_read_pool"]); public static int RedisMaxWritePool = int. parse (ConfigurationManager. deleetask[ "redis_max_write_pool"]); static RedisCacheHelper () {var redisHostStr = ConfigurationManager. deleetask[ "redis_server_session"]; if (! String. isNullOrEmpty (redisHostStr) {redisHosts = redisHostStr. split (','); if (redisHosts. length> 0) {pool = new PooledRedisClientManager (redisHosts, redisHosts, new partition () {MaxWritePoolSize = RedisMaxWritePool, MaxReadPoolSize = RedisMaxReadPool, AutoStart = true });}}} public static void Add <T> (string key, T value, DateTime expiry) {if (value = null) {return;} if (e Xpiry <= DateTime. Now) {Remove (key); return;} 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! {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 ;}try {if (pool! = Null) {using (var r = pool. GetClient () {if (r! = Null) {r. sendTimeout = 1000; r. set (key, value, slidingExpiration) ;}}} catch (Exception ex) {string msg = string. format ("{0 }:{ 1} exception! {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 msg = string. format ("{0 }:{ 1} exception! {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 msg = string. format ("{0 }:{ 1} exception! {2} "," cache "," delete ", key) ;}} public static bool Exists (string key) {try {if (pool! = Null) {using (var r = pool. GetClient () {if (r! = Null) {r. sendTimeout = 1000; return r. containsKey (key) ;}}} catch (Exception ex) {string msg = string. format ("{0 }:{ 1} exception! {2} "," cache "," Whether ", key) ;}return false ;}}}

Note: RedisCacheHelper uses the Client Connection Pool mode, which ensures the highest access efficiency. It also supports read/write splitting and load balancing.

 

3. Configuration File

    <!-- redis Start   -->    <add key="SessionExpireMinutes" value="180" />    <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 call

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

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.