第 7 章 高級主題
7.1 緩存
緩存是一種通過存儲資源的備份,在請求時返回資源備份的技術。ASP.NET Core 支持多種形式的緩存,既支持基于 HTTP 的緩存,也支持內(nèi)存緩存和分布式緩存,還提供響應緩存中間件
HTTP 緩存,服務端返回資源時,能夠在響應消息中包含 HTTP 緩存消息頭
驗證緩存資源的方式有兩種:
- 通過響應消息頭中的 Last-Modified
- 使用實體標簽消息頭
ASP.NET Core 提供的 [ResponseCache] 特性能夠為資源指定 HTTP 緩存行為
在 AuthorController 中為 GetAuthorAsync 方法添加該特性
[HttpGet("{authorId}", Name = nameof(GetAuthorAsync))]
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public async Task<ActionResult<AuthorDto>> GetAuthorAsync(Guid authorId)
請求該接口時,可以看到響應消息頭中包含了緩存信息
當應用中多個接口需要添加同樣的緩存行為時,為了避免重復,還可以使用緩存配置來完成同樣的功能
在 Startup 的 ConfigureServices 中添加
services.AddMvc(configure =>
{
configure.CacheProfiles.Add("Default", new CacheProfile {Duration = 60});
configure.CacheProfiles.Add("Never",
new CacheProfile {Location = ResponseCacheLocation.None, NoStore = true});
。。。
接著在特性中使用即可
[ResponseCache(CacheProfileName = "Default")]
當緩存的資源已經(jīng)過時后,客戶端需要到服務器驗證資源是否有效,可以通過實體標簽頭驗證
[HttpGet("{authorId}", Name = nameof(GetAuthorAsync))]
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public async Task<ActionResult<AuthorDto>> GetAuthorAsync(Guid authorId)
{
var author = await RepositoryWrapper.Author.GetByIdAsync(authorId);
if (author == null)
{
return NotFound();
}
var entityHash = HashFactory.GetHash(author);
Response.Headers[HeaderNames.ETag] = entityHash;
if (Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var requestETag) && entityHash == requestETag)
{
return StatusCode(StatusCodes.Status304NotModified);
}
var authorDto = Mapper.Map<AuthorDto>(author);
return authorDto;
}
GetHash 方法內(nèi)容如下:
namespace Library.API.Helpers
{
public class HashFactory
{
public static string GetHash(object entity)
{
string result = string.Empty;
var json = JsonConvert.SerializeObject(entity);
var bytes = Encoding.UTF8.GetBytes(json);
using (var hasher = MD5.Create())
{
var hash = hasher.ComputeHash(bytes);
result = BitConverter.ToString(hash);
result = result.Replace("-", "");
}
return result;
}
}
}
響應緩存中間件,使用它能夠為應用程序添加服務器端緩存功能
在 Startup 中配置響應緩存
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching(options =>
{
options.UseCaseSensitivePaths = true;
options.MaximumBodySize = 1024;
});
。。。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMapper mapper, ILoggerFactory loggerFactory)
{
app.UseResponseCaching();
。。。
添加響應緩存服務時,ResponseCachingOptions 包含3個屬性:
- SizeLimit:緩存大小
- MaximumBodySize:響應正文最大值
- UseCaseSensitivePaths:是否區(qū)分請求路徑大小寫
響應緩存中間件同樣使用特性設置
[ResponseCache(Duration = 60,VaryByQueryKeys = new string[]{"sortBy","searchQuery"})]
當服務端第二次接收同樣的請求時,它將從緩存直接響應客戶端
VaryByQueryKeys 屬性可以根據(jù)不同的查詢關鍵字來區(qū)分不同的響應
內(nèi)存緩存,利用服務器上的內(nèi)存來實現(xiàn)對數(shù)據(jù)的緩存
需要先在 Startup 中添加該服務
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
。。。
然后在需要緩存的位置注入 IMemoryCache 接口,并調(diào)用相關方法
public class BookController : ControllerBase
{
public IMapper Mapper { get; set; }
public IRepositoryWrapper RepositoryWrapper { get; set; }
public IMemoryCache MemoryCache { get; set; }
public BookController(IMapper mapper, IRepositoryWrapper repositoryWrapper, IMemoryCache memoryCache)
{
Mapper = mapper;
RepositoryWrapper = repositoryWrapper;
MemoryCache = memoryCache;
}
[HttpGet]
public async Task<ActionResult<List<BookDto>>> GetBooksAsync(Guid authorId)
{
List<BookDto> bookDtoList = new List<BookDto>();
string key = $"{authorId}_books";
if (!MemoryCache.TryGetValue(key, out bookDtoList))
{
var books = await RepositoryWrapper.Book.GetBookAsync(authorId);
bookDtoList = Mapper.Map<IEnumerable<BookDto>>(books).ToList();
MemoryCache.Set(key, bookDtoList);
}
//var books = await RepositoryWrapper.Book.GetBooksAsync(authorId);
//var bookDtoList = Mapper.Map<IEnumerable<BookDto>>(books);
return bookDtoList.ToList();
}
。。。
還可以使用 MemoryCacheEntryOptions 對象來控制緩存時間和優(yōu)先級
//MemoryCache.Set(key, bookDtoList);
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.AbsoluteExpiration = DateTime.Now.AddMinutes(10);
options.Priority = CacheItemPriority.Normal;
MemoryCache.Set(key, bookDtoList, options);
分布式緩存,有效解決內(nèi)存緩存不足的問題,由多個應用服務器共享
ASP.NET Core 使用分布式緩存,需要用到 IDistributedCache
ASP.NET Core 提供了 IDistributedCache 接口的3種實現(xiàn)方式:
- 分布式內(nèi)存緩存
- 分布式 SQLServer 緩存
- 分布式 Redis 緩存
分布式內(nèi)存緩存實際上并非分布式緩存,與內(nèi)存緩存一樣,可用于開發(fā)測試階段
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
services.AddDistributedMemoryCache();
}
else
{
// 使用其他分布式緩存
}
。。。
分布式 SQLServer 緩存使用前,需要使用命令 dotnet sql-cache create 創(chuàng)建緩存數(shù)據(jù)庫
dotnet sql-cache create “Date Source=(localdb)MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;” dbo TestCache
添加nuget
Install-Package Microsoft.Extensions.Caching.SqlServer
之后在容器種注入服務
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = Configuration["DistCache_ConnectionString"];
options.SchemaName = "dbo";
options.TableName = "TestCache";
});
。。。
分布式 Redis 緩存
添加nuget
Install-Package Microsoft.Extensions.Caching.Redis
之后在容器種注入服務
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
services.AddDistributedRedisCache(options =>
{
options.Configuration = Configuration["Caching:Host"];
options.InstanceName = Configuration["Caching:Instance"];
});
。。。
同時,在 appsettings.json 配置文件中添加 Redis 服務配置信息
"Caching": {
"Host": "127.0.0.1:6379",
"Instance": "master"
}
然后,在 AuthorController 注入 IDistributedCache 接口即可使用
public IDistributedCache DistributedCache { get; set; }
public AuthorController(IMapper mapper, IRepositoryWrapper repositoryWrapper, ILogger<AuthorController> logger, IDistributedCache distributedCache)
{
Mapper = mapper;
RepositoryWrapper = repositoryWrapper;
Logger = logger;
DistributedCache = distributedCache;
}
接下來,在 GetAuthorsAsync 方法中使用
public async Task<ActionResult<List<AuthorDto>>> GetAuthorsAsync([FromQuery] AuthorResourceParameters parameters)
{
PagedList<Author> pagedList = null;
// 為了簡單,僅當請求中不包含過濾和搜索查詢字符串時,才進行緩存,實際情況不應該有此限制
if (string.IsNullOrWhiteSpace(parameters.BirthPlace) && string.IsNullOrWhiteSpace(parameters.SearchQuery))
{
string cacheKey =
$"authors_page_{parameters.PageNumber}_pageSize_{parameters.PageSize}_{parameters.SortBy}";
string cacheContent = await DistributedCache.GetStringAsync(cacheKey);
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new PagedListConvert<Author>());
settings.Formatting = Formatting.Indented;
if (string.IsNullOrWhiteSpace(cacheContent))
{
pagedList = await RepositoryWrapper.Author.GetAllAsync(parameters);
DistributedCacheEntryOptions options = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(2)
};
var serializedContent = JsonConvert.SerializeObject(pagedList, settings);
await DistributedCache.SetStringAsync(cacheKey, serializedContent);
}
else
{
pagedList = JsonConvert.DeserializeObject<PagedList<Author>>(cacheContent, settings);
}
}
else
{
pagedList = await RepositoryWrapper.Author.GetAllAsync(parameters);
}
//var pagedList = await RepositoryWrapper.Author.GetAllAsync(parameters);
。。。
由于 Json.NET 在序列化集合對象時會將其作為數(shù)組處理,因而會忽略集合對象中的其他屬性,為了保留這些屬性,需要自定義 JsonConvert 類
namespace Library.API.Helpers
{
public class PagedListConvert<T> : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
PagedList<T> result = (PagedList<T>) value;
JObject jsonObj = new JObject();
jsonObj.Add("totalCount", result.TotalCount);
jsonObj.Add("pageNumber", result.CurrentPage);
jsonObj.Add("pageSize", result.PageSize);
jsonObj.Add("Items", JArray.FromObject(result.ToArray(), serializer));
jsonObj.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jsonObj = JObject.Load(reader);
var totalCount = (int) jsonObj["totalCount"];
var pageNumber = (int) jsonObj["pageNumber"];
var pageSize = (int) jsonObj["pageSize"];
var items = jsonObj["Items"].ToObject<T[]>(serializer);
PagedList<T> pageList = new PagedList<T>(items.ToList(), totalCount, pageNumber, pageSize);
return pageList;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(PagedList<T>);
}
}
}
本文摘自 :https://blog.51cto.com/u