using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; namespace Admin.Core.Common { public class CacheUtil : ICaching { //引用Microsoft.Extensions.Caching.Memory;这个和.net 还是不一样,没有了Httpruntime了 private readonly IMemoryCache _cache; //还是通过构造函数的方法,获取 public CacheUtil(IMemoryCache cache) { _cache = cache; } /// <summary> /// 取缓存项,如果不存在则返回空 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheKey"></param> /// <returns></returns> public T Get<T>(string cacheKey) { try { return (T)_cache.Get(cacheKey); } catch { return default; } } /// <summary> /// 使用键和值将某个缓存项插入缓存中,并指定基于时间的过期详细信息 /// </summary> /// <param name="cacheKey"></param> /// <param name="cacheValue"></param> /// <param name="timeSpan"></param> public void Set(string cacheKey, object cacheValue, int timeSpan) { // 缓存过期时间:分钟 var cacheTimeOut = Appsettings.app(new string[] { "AppSettings", "CacheTimeOut" }).ObjToInt(); _cache.Set(cacheKey, cacheValue, TimeSpan.FromSeconds(timeSpan == 0 ? cacheTimeOut : timeSpan * 60)); } /// <summary> /// 移除指定键的缓存项 /// </summary> /// <param name="key"></param> public void Remove(string key) { _cache.Remove(key); } } }