缓存的优点:
缓存的缺点:
缓存的地点:
Sticky Session:In-Memory 缓存存储在 Web 服务器的内存中,只有本服务器能访问到。当 Web 应用部署在多服务器时,需保证用户访问的服务器就是之前进行缓存的服务器。
通过 services.AddMemoryCache();
在 Startup ConfigureServices 中启用内存缓存。
MemoryCacheEntryOptions:
在 AlbumController 中使用 In-Memory Cache:
// GET: Album public async Task<ActionResult> Index() { if (!_memoryCache.TryGetValue( CacheEntryConstants.AlbumsOfToday, out List<Album> cachedAlbums)) { cachedAlbums = await _albumService.GetAllAsync(); var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(30)); cacheEntryOptions.RegisterPostEvictionCallback(FillCache, this); _memoryCache.Set(CacheEntryConstants.AlbumsOfToday, cachedAlbums, cacheEntryOptions); } return View(cachedAlbums); } private void FillCache(object key, object value, EvictionReason reason, object state) { // 不具体实现 Console.WriteLine("Cache entry is evicted!"); }
格式:
<cache>@await Component.InvokeAsync("xxx")</cache>
属性:
示例:
<cache expires-after="@TimeSpan.FromSeconds(30)"> @await Component.InvokeAsync("InternetStatus") </cache>
特点:
接口与常用方法:
类型:
Redis Cache
通过 Docker 安装 Redis:docker pull redis
如果拉取速度很慢,推荐使用阿里云的镜像加速器(简单教程)。
运行容器:docker run --name my-redis -d -p 6379:6379 redis
命名 暴露端口 6379 镜像名
docker ps
查看运行状态:
docker run -it --link my-redis:my-redis --rm redis redis-cli -h my-redis -p 6379
测试 redis:
打开 NuGet 安装 Redis:
在 Startup 中配置 Redis:
services.AddDistributedRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = "redis-for-albums"; });
在 AlbumController 中使用 Redis:
private readonly ILogger<AlbumController> _logger; private readonly IDistributedCache _distributedCache; private readonly IAlbumService _albumService; private readonly HtmlEncoder _htmlEncoder; public AlbumController( IAlbumService albumService, HtmlEncoder htmlEncoder, ILogger<AlbumController> logger, IDistributedCache distributedCache) { _albumService = albumService; _htmlEncoder = htmlEncoder; _logger = logger; _distributedCache = distributedCache; } // GET: Album public async Task<ActionResult> Index() { List<Album> cachedAlbums; var cachedAlbumsString = _distributedCache.Get(CacheEntryConstants.AlbumsOfToday); if (cachedAlbumsString == null) { cachedAlbums = await _albumService.GetAllAsync(); var serializedString = JsonConvert.SerializeObject(cachedAlbums); byte[] encodedAlbums = Encoding.UTF8.GetBytes(serializedString); var cacheEntryOptions = new DistributedCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(30)); _distributedCache.Set(CacheEntryConstants.AlbumsOfToday, encodedAlbums, cacheEntryOptions); } else { byte[] encodedAlbums = _distributedCache.Get(CacheEntryConstants.AlbumsOfToday); var serializedString = Encoding.UTF8.GetString(encodedAlbums); cachedAlbums = JsonConvert.DeserializeObject<List<Album>>(serializedString); } return View(cachedAlbums); }
参数:
在配置 MVC 中间件时配置 Response 缓存:
services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); options.Filters.Add<LogResourceFilter>(); options.CacheProfiles.Add("Default",new CacheProfile { Duration = 60 }); options.CacheProfiles.Add("Never", new CacheProfile { Location = ResponseCacheLocation.None, NoStore = true }); });
Response 缓存的使用:
// 手动配置 [ResponseCache(Duration = 30, Location = ResponseCacheLocation.Client)] public IActionResult Index() { _logger.LogInformation(MyLogEventIds.HomePage, "Visiting Home Index ..."); return View(); } // 通过指定 CacheProfile 进行配置 [ResponseCache(CacheProfileName = "Default")] public IActionResult Privacy() { return View(); }
注:
压缩传输的数据。通常针对 1K 以上的数据。
services.AddResponseCompression();//注册压缩服务
app.UseResponseCompression();
详细内容参考官方文档:Response compression in ASP.NET Core。
原文:https://www.cnblogs.com/cqqinjie/p/13322148.html