分散式快取
要利用分散式快取,你必須引用其中一個可用的實現:
例如,你將註冊 Redis 實現如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.Configuration = "ServerAdress";
options.InstanceName = "InstanceName";
});
}
在需要的地方需要 IDistributedCache
依賴:
public class BooksController {
private IDistributedCache distributedCache;
public BooksController(IDistributedCache distributedCache) {
this.distributedCache = distributedCache;
}
[HttpGet]
public async Task<Books[]> GetAllBooks() {
var serialized = this.distributedCache.GetStringAsync($"allbooks");
Books[] books = null;
if (string.IsNullOrEmpty(serialized)) {
books = await Books.FetchAllAsync();
this.distributedCache.SetStringAsync($"allbooks", JsonConvert.SerializeObject(books));
} else {
books = JsonConvert.DeserializeObject<Books[]>(serialized);
}
return books;
}
}