using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register MemoryCache
services.AddMemoryCache();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
app.UseMvcWithDefaultRoute();
}
}
再來 Contorller 以下設定
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace DoubleCheckedLocking.WebApplication.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private IMemoryCache _cache;
public ValuesController(IMemoryCache memoryCache)
{
this._cache = memoryCache;
}
// 取得快取值
var cacheEntry = this._cache.Get<DateTime>("key");
// 快取檢查
if (this._cache.Get<DateTime>("key") == null)
{
// 無快取, 所以重新取值
cacheEntry = DateTime.Now;
// 設定快取過期時間
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(3));
// 加入快取
_cache.Set("key", cacheEntry, cacheEntryOptions);
}
return cacheEntry.ToString();
}
}
}