.NET Core 缓存使用之 MemoryCache
目录
据时间过期的四种策略
首先说下:一般我们使用缓存都是根据时间设置过期策略的,常用的是以下四种过期策略:
1 永不过期:
永远不会过期
2 设置绝对过期时间点:
到期后就失效
3 设置过期滑动窗口:
只要在窗口期内访问,它的过期时间就一直向后顺延一个窗口长度
4 滑动窗口+绝对过期时间点:
只要在窗口期内访问,它的过期时间就一直向后顺延一个窗口长度,但最长不能超过绝对过期时间点
.NET Core 使用 MemoryCache
1) 在Startup.cs 中 配置 启用缓存
C# 全选
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// 启用缓存
services.AddMemoryCache();
}
2) 在控制器中使用 MemoryCache
C# 全选
public class WXHelperController : Controller
{
IMemoryCache _cache;
public WXHelperController(IMemoryCache cache)
{
_cache = cache;
}
}
3) 缓存扩展方法
C# 全选
public static class GZCacheExtensions
{
public static void GZSet<TItem>(this IMemoryCache cache, string key, TItem value, DateTime time)
{
cache.Set(key, value, time);
WriteCache(key, value, time);
}
public static TItem GZGet<TItem>(this IMemoryCache cache, string key)
{
var data = cache.Get<TItem>(key);
if (data == null)
{
DateTime time;
data = GetCache<TItem>(key, out time);
if (data != null)
{
cache.Set(key, data, time);
}
}
return data;
}
static TItem GetCache<TItem>(string cacheKey, out DateTime expireTime)
{
string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache");
string _filepath = System.IO.Path.Combine(filePath, cacheKey + ".cache");
if (System.IO.File.Exists(_filepath))
{
try
{
string json = File.ReadAllText(_filepath);
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<CacheData>(json);
expireTime = data.ExpireTime;
if (data.ExpireTime <= DateTime.Now)
{
File.Delete(_filepath);
return default(TItem);
}
return (data.Value as JToken).ToObject<TItem>();
}
catch
{
File.Delete(_filepath);
expireTime = DateTime.Now;
return default(TItem);
}
}
expireTime = DateTime.Now;
return default(TItem);
}
static void WriteCache<TItem>(string cacheKey, TItem value, DateTime expireTime)
{
string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache");
string _filepath = System.IO.Path.Combine(filePath, cacheKey + ".cache");
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
}
//设置缓存数据的相关参数
CacheData data = new CacheData() { Value = value, ExpireTime = expireTime };
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
Write(_filepath, json);
}
static void Write(string file, string content)
{
FileStream fs = new FileStream(file, FileMode.Create);
//获得字节数组
byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
}
public class CacheData
{
/// <summary>
/// 值
/// </summary>
public object Value { get; set; }
/// <summary>
/// 到期时间
/// </summary>
public DateTime ExpireTime { get; set; }
}
其他参考代码
using Microsoft.Extensions.Caching.Memory; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace server.Models { public class CacheManager { public static CacheManager Default = new CacheManager(); private IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions()); /// <summary> /// 判断是否在缓存中 /// </summary> /// <param name="key">关键字</param> /// <returns></returns> public bool IsInCache(string key) { List<string> keys = GetAllKeys(); foreach (var i in keys) { if (i == key) return true; } return false; } /// <summary> /// 获取所有缓存键 /// </summary> /// <returns></returns> public List<string> GetAllKeys() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var entries = _cache.GetType().GetField("_entries", flags).GetValue(_cache); var cacheItems = entries as IDictionary; var keys = new List<string>(); if (cacheItems == null) return keys; foreach (DictionaryEntry cacheItem in cacheItems) { keys.Add(cacheItem.Key.ToString()); } return keys; } /// <summary> /// 获取所有的缓存值 /// </summary> /// <returns></returns> public List<T> GetAllValues<T>() { var cacheKeys = GetAllKeys(); List<T> vals = new List<T>(); cacheKeys.ForEach(i => { T t; if (_cache.TryGetValue<T>(i, out t)) { vals.Add(t); } }); return vals; } /// <summary> /// 取得缓存数据 /// </summary> /// <typeparam name="T">类型值</typeparam> /// <param name="key">关键字</param> /// <returns></returns> public T Get<T>(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T value; _cache.TryGetValue<T>(key, out value); return value; } /// <summary> /// 设置缓存(永不过期) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_NotExpire<T>(string key, T value) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value); } /// <summary> /// 设置缓存(滑动过期:超过一段时间不访问就会过期,一直访问就一直不过期) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_SlidingExpire<T>(string key, T value, TimeSpan span) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value, new MemoryCacheEntryOptions() { SlidingExpiration = span }); } /// <summary> /// 设置缓存(绝对时间过期:从缓存开始持续指定的时间段后就过期,无论有没有持续的访问) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_AbsoluteExpire<T>(string key, T value, TimeSpan span) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value, span); } /// <summary> /// 设置缓存(绝对时间过期+滑动过期:比如滑动过期设置半小时,绝对过期时间设置2个小时,那么缓存开始后只要半小时内没有访问就会立马过期,如果半小时内有访问就会向后顺延半小时,但最多只能缓存2个小时) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_SlidingAndAbsoluteExpire<T>(string key, T value, TimeSpan slidingSpan, TimeSpan absoluteSpan) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value, new MemoryCacheEntryOptions() { SlidingExpiration = slidingSpan, AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(absoluteSpan.Milliseconds) }); } /// <summary> /// 移除缓存 /// </summary> /// <param name="key">关键字</param> public void Remove(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); _cache.Remove(key); } /// <summary> /// 释放 /// </summary> public void Dispose() { if (_cache != null) _cache.Dispose(); GC.SuppressFinalize(this); } } }
GarsonZhang www.yesdotnet.com
参考地址: https://blog.csdn.net/u010476739/article/details/102947433
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员