ASP.NET Core MVC Cache
一、IN-memory 缓存
>存储在服务器内存中的缓存(缺点:缓存存放在哪台服务器上,执行的方法就应该在哪一台服务器上,否则会读取不到数据)
>Sticky Session 黏性会话
>适用于任何对象
添加服务
services.AddMemoryCache();
注入服务IMemoryCache memoryCache
添加cache Key类
public class CacheEntryConstants
{
public const string DataToday = nameof(DataToday);
}
使用缓存并配置缓存
如果读取到了缓存,就会直接return,否则会添加到缓存,下次读取的时候检查缓存存在该对象直接return;
public IActionResult GetAll()
{
//save to the cache if momerycache do not have cache Record
//else just get the MoviesInstance from EntitySqlserver
if (!_memoryCache.TryGetValue(CacheEntryConstants.DataToday, out List<MoviesInstanceClass> cacheMovies))
{
cacheMovies = _moviesInterface.GetMovies();
var cacheOptions = new MemoryCacheEntryOptions()
//如果这个值被访问了,有效期延长30s
.SetSlidingExpiration(TimeSpan.FromSeconds(30))
//绝对的日期
.SetAbsoluteExpiration(TimeSpan.FromSeconds(600));
//回调函数(缓存被清楚后调用方法,把缓存再填充回去)
cacheOptions.RegisterPostEvictionCallback(FillCache, this);
//设置缓存的值
_memoryCache.Set(CacheEntryConstants.DataToday, cacheMovies, cacheOptions);
}
return View("~/Views/Home/MovieList.cshtml", cacheMovies);
}
二、Cache Tag Helper缓存
>属性(查阅官方文档)
服务器端
使用IMemoryCache
<cache>@await Component.InvokeAsync("")</cache>
三、分布式缓存
>无需Sticky Session
>可扩展
>服务器重启不会影响缓存(缓存服务器重启就不一定了~)
>性能更好
分布式缓存种类
分布式 Memory Cache 开发时使用
分布式 Sqlserver cache 生产的时候使用
分布式 Redis Cache 生产的时候用的多一些

浙公网安备 33010602011771号