RedisUtil(未完,持续更新中....)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using StackExchange.Redis; namespace Common.Util { public class RedisUtil { #region init private static object lockForRedis = new object();//连接实例锁 private static ConnectionMultiplexer Instance; //连接实例 /// <summary> /// 默认开始就给连接 /// </summary> static RedisUtil() { GetConn(); //--初始就实例化 } /// <summary> /// 获取连接 /// </summary> /// <returns></returns> private static ConnectionMultiplexer GetConn() { if (Instance == null) { lock (lockForRedis) { if (Instance == null || !Instance.IsConnected) { Instance = ConnectionMultiplexer.Connect(GetConfig()); } } } return Instance; } /// <summary> /// 获取配置 /// </summary> /// <returns></returns> private static ConfigurationOptions GetConfig() { ConfigurationOptions options = new ConfigurationOptions(); options.EndPoints.Add("localhost",6379); options.ConnectTimeout = 6000; //超时时间设置(默认5000) options.ConnectRetry = 1; //连接重试周期 return options; } #endregion #region String /// <summary> /// 设置String值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="timeSpan"></param> /// <param name="dbIndex"></param> /// <returns></returns> public static bool StringSet<T>(string key,T value,TimeSpan? timeSpan=null,int dbIndex=0) { try { var db = GetConn().GetDatabase(dbIndex); return db.StringSet(key, JsonConvert.SerializeObject(value),timeSpan); } catch (Exception ex) { Console.WriteLine(ex); return false; } } /// <summary> /// 获取String值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="dbIndex"></param> /// <returns></returns> public static T StringGet<T>(string key,int dbIndex=0) { try { var db = GetConn().GetDatabase(dbIndex); return JsonConvert.DeserializeObject<T>(db.StringGet(key)); } catch(Exception ex) { Console.WriteLine(ex); return default(T); } } /// <summary> /// 存入递增类型的键值 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dbIndex"></param> /// <returns></returns> public static double StringIncrement(string key, double value, int dbIndex = 0) { try { var db = GetConn().GetDatabase(dbIndex); return db.StringIncrement(key,value); } catch (Exception ex) { return 0; } } /// <summary> /// 存入递减类型的键值 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dbIndex"></param> /// <returns></returns> public static double StringDecrement(string key,double value,int dbIndex = 0) { try { var db = GetConn().GetDatabase(dbIndex); return db.StringDecrement(key, value); } catch (Exception ex) { return 0; } } #endregion } }
力争写最通俗易懂的文章,不添加任何防腐剂~~~