using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace OS.Common.Modules.CacheModule { /// /// /// public static class CacheUtil { private static readonly ConcurrentDictionary _cacheDirs = new ConcurrentDictionary(); /// /// 通过模块名称获取 /// /// /// public static ICache GetCache(string cacheModule) { if (string.IsNullOrEmpty(cacheModule)) cacheModule = ModuleNames.Default; if (_cacheDirs.ContainsKey(cacheModule)) return _cacheDirs[cacheModule]; var cache = OsConfig.Provider.GetCache(cacheModule) ?? new Cache(); _cacheDirs.TryAdd(cacheModule, cache); return cache; } /// /// 添加缓存,已存在不更新 /// /// 添加缓存对象类型 /// 添加对象的key /// 值 /// 相对过期的TimeSpan, 如果使用固定时间 =TimeSpan.Zero /// 绝对过期时间 /// 模块名称 /// 缓存分区名称 /// 是否添加成功 public static bool Add(string key, T obj, TimeSpan slidingExpiration, DateTime? absoluteExpiration = null, string moduleName = ModuleNames.Default, int db = 0) { return GetCache(moduleName).Add(key, obj, slidingExpiration, absoluteExpiration, db); } /// /// 添加缓存,如果存在则更新 /// /// 添加缓存对象类型 /// 添加对象的key /// 值 /// 相对过期的TimeSpan,如果使用固定时间 =TimeSpan.Zero /// 绝对过期时间 /// 模块名称 /// 缓存分区db /// 是否添加成功 public static bool AddOrUpdate(string key, T obj, TimeSpan slidingExpiration, DateTime? absoluteExpiration = null, string moduleName = ModuleNames.Default, int db = 0) { return GetCache(moduleName).AddOrUpdate(key, obj, slidingExpiration, absoluteExpiration, db); } /// /// 获取缓存对象 /// /// 获取缓存对象类型 /// key /// 模块名称 /// 缓存分区db /// 获取指定key对应的值 public static T Get(string key, string moduleName = ModuleNames.Default, int db = 0) { return GetCache(moduleName).Get(key, db); } /// /// 移除缓存对象 /// /// /// /// 模块名称 /// 是否成功 public static bool Remove(string key, string moduleName = ModuleNames.Default, int db = 0) { return GetCache(moduleName).Remove(key, db); } /// /// 判断是否存在缓存对象 /// /// key值 /// 模块名称 /// 缓存分区db /// public static bool Contains(string key, string moduleName = ModuleNames.Default, int db = 0) { return GetCache(moduleName).Contains(key, db); } } }