一个常用的RedisHelper类( 二 )

/// <summary>//Dictionary<string, User> dic = new Dictionary<string, User>();/// dic.Add("1", new User() { age = 99, name = "A01" });/// dic.Add("2", new User() { age = 99, name = "A02" });/// redis.SetHashFieldCache("users", dic);/// </summary>/// <typeparam name="T"></typeparam>/// <param name="key"></param>/// <param name="dict"></param>/// <returns></returns>public int SetHashFieldCache<T>(string key, Dictionary<string, T> dict){int count = 0;var jsonOption = new JsonSerializerSettings(){ReferenceLoopHandling = ReferenceLoopHandling.Ignore};foreach (string fieldKey in dict.Keys){string fieldValue = https://www.isolves.com/it/sjk/Redis/2022-03-21/JsonConvert.SerializeObject(dict[fieldKey], jsonOption);count += cache.HashSet(key, fieldKey, fieldValue) ? 1 : 0;}return count;}/// <summary>/// var d = redis.GetHashFieldCache<User>("users", "1");/// </summary>/// <typeparam name="T"></typeparam>/// <param name="key"></param>/// <param name="fieldKey"></param>/// <returns></returns>public T GetHashFieldCache<T>(string key, string fieldKey){var dict = GetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, default(T) } });return dict[fieldKey];}public Dictionary<string, T> GetHashFieldCache<T>(string key, Dictionary<string, T> dict){foreach (string fieldKey in dict.Keys){string fieldValue = https://www.isolves.com/it/sjk/Redis/2022-03-21/cache.HashGet(key, fieldKey);dict[fieldKey] = JsonConvert.DeserializeObject(fieldValue);}return dict;}public Dictionary<string, T> GetHashCache<T>(string key){Dictionary<string, T> dict = new Dictionary<string, T>();var hashFields = cache.HashGetAll(key);foreach (HashEntry field in hashFields){dict[field.Name] = JsonConvert.DeserializeObject<T>(field.Value);}return dict;}/// <summary>/// 将Hash转换成List/// </summary>/// <typeparam name="T"></typeparam>/// <param name="key"></param>/// <returns></returns>public List<T> GetHashToListCache<T>(string key){List<T> list = new List<T>();var hashFields = cache.HashGetAll(key);foreach (HashEntry field in hashFields){list.Add(JsonConvert.DeserializeObject<T>(field.Value));}return list;}/// <summary>/// redis.RemoveHashFieldCache("users", "1");/// </summary>/// <param name="key"></param>/// <param name="fieldKey"></param>/// <returns></returns>public bool RemoveHashFieldCache(string key, string fieldKey){Dictionary<string, bool> dict = new Dictionary<string, bool> { { fieldKey, false } };dict = RemoveHashFieldCache(key, dict);return dict[fieldKey];}public Dictionary<string, bool> RemoveHashFieldCache(string key, Dictionary<string, bool> dict){foreach (string fieldKey in dict.Keys){dict[fieldKey] = cache.HashDelete(key, fieldKey);}return dict;}/// <summary>/// 释放/// </summary>public void Dispose(){if (connection != null){connection.Close();}GC.SuppressFinalize(this);}



推荐阅读