AspnetCore 缓存篇
一, 缓存的作用
怎样理解缓存:
其实所有的程序, 架构, 优化, 线程... 等技术手段, 最终的目的都是如何使产品快速的响应用户的操作, 提高用户的体验性, 目标都是为了系统的使用者, 缓存的存在也是同样的道理, 缓存常用于存放不经常更改的数据信息, 比如, 用户的基础数据, Token 等一些长被使用并且不常更改的.
举例说明
咱们就拿用户的登录操作来说, 有一个系统是这样设计的,(1)用户 (输入用户名: 密码) 登录(2)首先程序做的是在缓存中查询数据, 判断是否有缓存存在, 缓存是否过期, 如果缓存过期了(3)进库查询用户是否具有登录的权限最后是功能页面. 一张简单的图加深一下印象
在上图中我们可以看到如果缓存存在的话, 我们大可不必进库去查询数据了, 省去了查询的动作, 开关库, 判断的操作. 加入这些动作可以省去 1 秒钟的时间, 这就已经在提高用户的体验性了.
缓存的作用不只是这一个方面, 建议大家多去找找资料, 每个人学出来的东西都不一样.
比如缓存的状态, 生存期, 缓存的类别 等
二, ASPNet Core 的内置缓存
AspNetCore 支持多种缓存, 首先说一下 AspNetCore 的内置缓存 IMemoryCache https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.memory.imemorycache ,
IMemoryCache https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.memory.imemorycache 把数据存储在 web 服务器的内置缓存中, 也就是 Web 服务器缓存, 和 System.Web.HttpRuntime 缓存作用上差别不大 , 但是在 Core 中去掉了 System.Web.HttpRuntime 的命名引用被移除, 引入命名空间 Microsoft.Extensions.Caching.Memory
使用 NuGet 管理工具添加如下:
针对 Core 缓存我们做出如下几个操作:
1. 首先创建一个缓存:
操作步骤引入命名空间, Microsoft.Extensions.Caching.Memory
在我们的帮助类中用构造器注入的方式创建 IMemoryCache 的对象
代码如下
- private IMemoryCache _cache;
- // 构造器注入
- public CoreMemoryCache(IMemoryCache memoryCache)
- {
- _cache = memoryCache;
- }
- View Code
创建缓存的方法有两个:
(1) Set(); 创建一个缓存项, 可以设置缓存项的绝对和滑动过期时间, 优先级等.
(2) GetOrCreate(); 方法的含义和命名一致, 获取或创建, 如果缓存存在则获取缓存项, 如果不存在则创建缓存项.
代码如下
(1)Set();
- public bool Add(string key, object value)
- {
- if (string.IsNullOrEmpty(key))
- {
- #region ArgumentNullException 说明
- /*
- * 如果不想返回异常信息的话也可以返回 自己定义的
- * 当参数为空时放生的异常
- * 和 ArgumentException 作用相同
- */
- #endregion
- // throw new ArgumentNullException(key);
- }
- else
- {
- MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
- cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
- cacheExpirationOptions.Priority = CacheItemPriority.Normal;
- cacheExpirationOptions.RegisterPostEvictionCallback(IDGCacheItemChangedHandler, this);
- // 添加
- // 类似 System.Web.HttpRuntime.Cache[key]
- _cache.Set(key, value, cacheExpirationOptions);
- }
- // 如果添加成功则验证是否存在返回 True 或 false
- return Exists(key);
- }
设置缓存的 CacheItemPriority
View Code
添加缓存的时候利用 MemoryCacheEntryOptions 来设置缓存: 重点
具体实现:
利用缓存中 Set 方法最后一个参数 上方截图
MemoryCacheEntryOptions: 绝对重要, 他决定着怎么设置绝对过期时间和滑动过期时间, 优先级等
缓存添加实现如下
- MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
- // 绝对过期时间
- cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
- // 缓存优先级
- cacheExpirationOptions.Priority = CacheItemPriority.Normal;
- // 添加缓存
- _cache.Set(key, value, cacheExpirationOptions);
- View Code
MemoryCacheEntryOptions 的 Priority 属性. Priority 属性指定应将哪些对象 (基于已设置的优先级) 从缓存中删除, 作为每当 Web 服务器内存空间不足时回收内存的运行时策略的一部分. 要设置优先级, 我们使用 CacheItemPriority 枚举. 这可以具有以下可能的值之一: 低, 正常, 高和 NeverRemove. ASP.Net Core 中的内存缓存提供程序将在内存压力下移除缓存条目, 如果将缓存优先级设置为 CacheItemPriority.NeverRemove. 这个时候我们可以注册一个回调, 该回调将在从缓存中移除条目时执行
MemoryCacheEntryOptions 中的 RegisterPostEvictionCallback 这个可以用来记录日志什么的
举例代码如下:
- cacheExpirationOptions.RegisterPostEvictionCallback(AddCallback,this);
- //public enum EvictionReason
- //{
- // None = 0,
- ////
- //// 摘要:
- //// Manually
- // Removed = 1,
- ////
- //// 摘要:
- //// Overwritten
- // Replaced = 2,
- ////
- //// 摘要:
- //// Timed out
- // Expired = 3,
- ////
- //// 摘要:
- //// Event
- // TokenExpired = 4,
- ////
- //// 摘要:
- //// Overflow
- // Capacity = 5
- //}
- public void AddCallback(object key, object value, EvictionReason reason, object state)
- {
- _cache.Set("CallbackMsg", reason);
- }
- (2)GetOrCreate();
代码如下:
代码如下:
- /// <summary>
- /// 存在创建不存在获取
- /// </summary>
- /// <param name="key"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public bool AddOrCreate(string key, object value)
- {
- if (string.IsNullOrEmpty(key))
- { }
- else
- {
- // public static TItem GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory);
- _cache.GetOrCreate(key, ENTRY => { return value; });
- }
- // 如果添加成功则验证是否存在
- return Exists(key);
- }
- View Code
2. 删除缓存
(1) Remove();
这个见名就知道了
代码如下:
- /// <summary>
- /// 删除缓存
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public bool Remove(string key)
- {
- if (string.IsNullOrEmpty(key))
- {
- return false;
- }
- else
- {
- // 删除
- _cache.Remove(key);
- // 如果删除成功则验证是否存在返回 bool
- return !Exists(key);
- }
- }
- View Code
3. 修改缓存
(1)修改缓存并没有具体的方法, 咱们代码走的是, 先删除后添加的方法
代码如下:
- /// <summary>
- /// 修改缓存
- /// </summary>
- /// <param name="key"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- /// 修改时 MemoryCache 没有提供相对相应的方法, 先删除后添加
- public bool Modify(string key, object value)
- {
- bool ReturnBool = false;
- if (string.IsNullOrEmpty(key))
- { }
- else
- {
- if (Exists(key))
- {
- // 删除
- if (!Remove(key))
- {
- ReturnBool = Add(key, value);
- }
- }
- }
- return ReturnBool;
- View Code
4. 获取缓存项
(1)Get();
代码如下:
- /// <summary>
- /// 获取缓存
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public object Get(string key)
- {
- if (string.IsNullOrEmpty(key))
- {
- return false;
- }
- else
- {
- #region 另一种判断方式
- /*
- _cache.TryGetValue(key, out ReturnValue)检索缓存输出 Bool;
- 用这个也可以直接把 out 输出就行
- */
- #endregion
- return _cache.Get(key);
- }
- }
- View Code
5. 验证缓存是否存在
代码如下: 利用 TryGetValue();
- /// <summary>
- /// 验证缓存是否存在
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public bool Exists(string key)
- {
- object ReturnValue;
- if (string.IsNullOrEmpty(key))
- {
- return false;
- }
- else
- {
- return _cache.TryGetValue(key, out ReturnValue);
- }
- }
- View Code
缓存中整体的方法, 不过有的没去实现
下面是所有方法的截图:
睡觉了一点半了, 后面写的有点捉急抱歉,
来源: https://www.cnblogs.com/szlblog/p/9022607.html