.Net Core框架中有两个内存接口:
- IMemoryCache:内存缓存接口,内存缓存可以存储任何对象
- IDistributedCache:分布式缓存接口(Redis、MongoDB、DB...)
微软缓存组件源码在:https://github.com/aspnet/Caching
内存缓存(MemoryCache)
如何使用
1、安装程序集:System.Runtime.Caching 和 Microsoft.Extensions.Caching.Memory,如果是是Core MVC程序自带的Microsoft.AspNetCore.App包里已经涵盖了 Microsoft.Extensions.Caching.Memory,无需重复下载。
2、在ConfigureService中注册内存缓存服务: services.AddMemoryCache();
3、构造函数注入 IMemoryCache
IMemoryCache
内存缓存接口只有三个方法
public interface IMemoryCache : IDisposable
{
ICacheEntry CreateEntry(object key);//添加一个缓存
void Remove(object key);//删除一个缓存
bool TryGetValue(object key, out object value);//获取一个缓存(并可得到具体的缓存是否存在)
}
ICacheEntry代表一条缓存
public interface ICacheEntry : IDisposable
{
DateTimeOffset? AbsoluteExpiration{get;set;}
TimeSpan? AbsoluteExpirationRelativeToNow{get;set;}
IList<IChangeToken> ExpirationTokens{get;}
object Key{get;}
IList<PostEvictionCallbackRegistration> PostEvictionCallbacks{get;}
CacheItemPriority Priority{get;set;}
long? Size{get;set;}
TimeSpan? SlidingExpiration{get;set;}
object Value{get;set;}
- Key 缓存key
- Value 缓存值
- AbsoluteExpiration 绝对过期时间,为null则条件无效
- AbsoluteExpirationRelativeToNow 相对当前时间的绝对过期时间(使用TimeSpan),为null条件无效
- SlidingExpiration 滑动过期时间
- ExpirationTokens 提供用来自定义缓存过期
- PostEvictionCallbacks 缓存失效回调
- Priority 缓存项优先级(在缓存满载的时候决定清除的顺序)
- Size 代表缓存数据的大小,在内存缓存中一般为null
演示:
IMemoryCache cache = new MemoryCache(Options.Create(new MemoryCacheOptions())); ;
using (ICacheEntry cacheEntry = cache.CreateEntry("k1"))
{
cacheEntry.SetValue("v1");
}
string v1 = cache.Get<string>("k1");
MS提供了IMemoryCache扩展方法类CacheExtensions
CacheExtensions:
public static class CacheExtensions
{
public static object Get(this IMemoryCache cache, object key){}
public static Task<TItem> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory){}
public static TItem GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory){}
public static TItem Get<TItem>(this IMemoryCache cache, object key){}
public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value){}
public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options){}
public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, IChangeToken expirationToken){}
public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, DateTimeOffset absoluteExpiration){}
public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow){}
public static bool TryGetValue<TItem>(this IMemoryCache cache, object key, out TItem value){}
}
分布式缓存(IDistributedCache)
IDistributedCache:
public interface IDistributedCache
{
//获取
byte[] Get(string key);
Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken));
//刷新并重置其过期超时的值(如果有)
void Refresh(string key);
Task RefreshAsync(string key, CancellationToken token = default(CancellationToken));
//删除
void Remove(string key);
Task RemoveAsync(string key, CancellationToken token = default(CancellationToken));
//添加
void Set(string key, byte[] value, DistributedCacheEntryOptions options);
Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));
}
Redis分布式缓存如何使用
安装 Microsoft.Extensions.Caching.Redis包
控制台中使用:
static void Main(string[] args)
{
//RedisCache实现了接口IDistributedCache
RedisCache redisCache = new RedisCache(new RedisCacheOptions() {
Configuration="192.168.254.134:6379",
InstanceName="test"
});
redisCache.SetString("key","value");
var val = redisCache.GetString("key");
}
asp.net core中使用:
//将Redis分布式缓存服务添加到服务中
services.AddDistributedRedisCache(options =>
{
//Redis实例名
options.InstanceName = "RedisDistributedCache";
options.ConfigurationOptions = new ConfigurationOptions()
{
ConnectTimeout = 2000,
DefaultDatabase = 1,
//Password = "xxxxxx",
AllowAdmin = true,
AbortOnConnectFail = false,//当为true时,当没有可用的服务器时则不会创建一个连接
};
options.ConfigurationOptions.EndPoints.Add("xxxxxx:6379");
});
需要缓存的服务中注入IDistributedCache即可:
public HomeController(IDistributedCache Cache){}
MongoDB分布式缓存如何使用
安装 MarkCBB.Extensions.Caching.MongoDB 包
控制台中使用:
static void Main(string[] args)
{
MongoDBCache mongoDBCache = new MongoDBCache(new MongoDBCacheOptions()
{
ConnectionString = "mongodb://192.168.254.135:27017",
DatabaseName = "sample",
CollectionName = "sample"
});
mongoDBCache.Set("username", Encoding.UTF8.GetBytes("jack"), new DistributedCacheEntryOptions()
{
AbsoluteExpiration = DateTime.Now.AddDays(1)
});
var info = mongoDBCache.GetString("username");
}
案例
案例1: 如何清除缓存?
通过IChangeToken清除缓存
public class CacheProvider
{
private static CancellationTokenSource _resetCacheToken = new CancellationTokenSource();
private readonly IMemoryCache _innerCache;
public T Set<T>(object key, T value)
{
var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal).SetAbsoluteExpiration(typeExpiration);
options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
_innerCache.Set(CreateKey(type, key), value, options);
return value;
}
public void Reset()
{
if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled)
{
_resetCacheToken.Cancel();
_resetCacheToken.Dispose();
}
_resetCacheToken = new CancellationTokenSource();
}
}
参考:
https://www.cnblogs.com/ants/p/8477223.html