自己项目中使用的Redis帮助类,采用StackExchange.Redis库,单例模式,使用简单,直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| #region Redis缓存
private static readonly object _locker = new object();
static ConnectionMultiplexer redis;
static ConnectionMultiplexer Redis { get { if (redis == null) { lock (_locker) { if (redis == null || !redis.IsConnected) { redis = GetRedis(); } } } return redis; } }
private static ConnectionMultiplexer GetRedis() { return ConnectionMultiplexer.Connect(System.Configuration.ConfigurationManager.ConnectionStrings["RedisStr"].ConnectionString); }
public static bool CacheDataKeyExists(string id) { return Redis.GetDatabase().KeyExists(id); }
public static void CacheDataSave<T>(string id, T data, TimeSpan? expiry = null) { using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize<T>(ms, data); Redis.GetDatabase().StringSet(id, ms.ToArray(), expiry); } }
public static void FixDataExpiry(string id, TimeSpan? expiry = null) { if (CacheDataKeyExists(id)) { Redis.GetDatabase().KeyExpire(id, expiry); } }
public static T CacheDataGet<T>(string id) { var _bytes = Redis.GetDatabase().StringGet(id); using (MemoryStream ms = new MemoryStream(_bytes)) { var _data = Serializer.Deserialize<T>(ms); return _data; } }
public static List<RedisKey> CacheDataKeysGet(string pattern) { var values = Redis.GetServer(Redis.GetEndPoints()[0]).Keys(pattern: pattern); return values.ToList(); }
public static void CacheDataRemove(string key) { Redis.GetDatabase().KeyDelete(key); } #endregion
|
使用过程中如果出现timeout异常,可以参考我的另一篇文章:
StackExchange.Redis timeout异常 解决方案