C# 操作redis
生活随笔
收集整理的這篇文章主要介紹了
C# 操作redis
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
下載 redis windows?版本?官網(wǎng)目前沒有windows安裝下載,下載地址為?
https://github.com/MicrosoftArchive/redis/releases??
直接點(diǎn)擊安裝?一直下一步
我的安裝路徑??D:\Program Files\Redis
啟動命令行工具?測試redis
?
C#? 連接redis?在項(xiàng)目類庫引用上右鍵啟動NuGet?搜索redis?安裝以下二個框架
redis工具類
public class RedisCacheHelper{private static readonly PooledRedisClientManager pool = null;private static readonly string[] redisHosts = null;public static int RedisMaxReadPool = 3;public static int RedisMaxWritePool = 1;static RedisCacheHelper(){var redisHostStr = "127.0.0.1:6379";if (!string.IsNullOrEmpty(redisHostStr)){redisHosts = redisHostStr.Split(',');if (redisHosts.Length > 0){pool = new PooledRedisClientManager(redisHosts, redisHosts,new RedisClientManagerConfig(){MaxWritePoolSize = RedisMaxWritePool,MaxReadPoolSize = RedisMaxReadPool,AutoStart = true});}}}#region Addpublic static void Add<T>(string key, T value, DateTime expiry){if (value == null){return;}if (expiry <= 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}發(fā)生異常!{2}", "cache", "存儲", 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}發(fā)生異常!{2}", "cache", "存儲", 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}發(fā)生異常!{2}", "cache", "獲取", key);}return obj;}#endregionpublic 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}發(fā)生異常!{2}", "cache", "刪除", 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}發(fā)生異常!{2}", "cache", "是否存在", key);}return false;}} View Code?
測試操作?
?測試
?
轉(zhuǎn)載于:https://www.cnblogs.com/freexiaoyu/p/10273111.html
總結(jié)
以上是生活随笔為你收集整理的C# 操作redis的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python之协程
- 下一篇: Java反射中method.isBrid