using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Caching.Memory; using YiSha.Cache.Interface; using YiSha.Util; namespace YiSha.MemoryCache { public class MemoryCacheImp : ICache { private IMemoryCache cache = GlobalContext.ServiceProvider.GetService(); public bool SetCache(string key, T value, DateTime? expireTime = null) { try { if (expireTime == null) { return cache.Set(key, value) != null; } else { return cache.Set(key, value, (expireTime.Value - DateTime.Now)) != null; } } catch (Exception ex) { LogHelper.Error(ex); } return false; } public bool RemoveCache(string key) { cache.Remove(key); return true; } public T GetCache(string key) { var value = cache.Get(key); return value; } #region Hash public int SetHashFieldCache(string key, string fieldKey, T fieldValue) { return SetHashFieldCache(key, new Dictionary { { fieldKey, fieldValue } }); } public int SetHashFieldCache(string key, Dictionary dict) { int count = 0; foreach (string fieldKey in dict.Keys) { count += cache.Set(key, dict) != null ? 1 : 0; } return count; } public T GetHashFieldCache(string key, string fieldKey) { var dict = GetHashFieldCache(key, new Dictionary { { fieldKey, default(T) } }); return dict[fieldKey]; } public Dictionary GetHashFieldCache(string key, Dictionary dict) { var hashFields = cache.Get>(key); foreach (KeyValuePair keyValuePair in hashFields.Where(p => dict.Keys.Contains(p.Key))) { dict[keyValuePair.Key] = keyValuePair.Value; } return dict; } public Dictionary GetHashCache(string key) { Dictionary dict = new Dictionary(); var hashFields = cache.Get>(key); foreach (string field in hashFields.Keys) { dict[field] = hashFields[field]; } return dict; } public List GetHashToListCache(string key) { List list = new List(); var hashFields = cache.Get>(key); foreach (string field in hashFields.Keys) { list.Add(hashFields[field]); } return list; } public bool RemoveHashFieldCache(string key, string fieldKey) { Dictionary dict = new Dictionary { { fieldKey, false } }; dict = RemoveHashFieldCache(key, dict); return dict[fieldKey]; } public Dictionary RemoveHashFieldCache(string key, Dictionary dict) { var hashFields = cache.Get>(key); foreach (string fieldKey in dict.Keys) { dict[fieldKey] = hashFields.Remove(fieldKey); } return dict; } #endregion } }