- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProgram.cs
54 lines (45 loc) · 2.08 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
usingMicrosoft.Extensions.Caching.Memory;
usingMicrosoft.Extensions.FileProviders;
stringCACHE_KEY="MyCache";
varbuilder=WebApplication.CreateBuilder();
builder.Services.AddMemoryCache();
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddFilter((provider,category,logLevel)=>!category.Contains("Microsoft.AspNetCore"));
varapp=builder.Build();
varfileProvider=newPhysicalFileProvider(app.Environment.ContentRootPath);
app.Run(async context =>
{
varlog=context.RequestServices.GetService<ILoggerFactory>().CreateLogger("app");
varcache=context.RequestServices.GetService<IMemoryCache>();
vargreeting=cache.Get(CACHE_KEY)asstring;
//There is no existing cache, add one
if(string.IsNullOrWhiteSpace(greeting))
{
varoptions=newMemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(5))
.RegisterPostEvictionCallback((objectkey,objectvalue,EvictionReasonreason,objectstate)=>
{
if(state==null)
log.LogInformation("State is null");
log.LogInformation($"Key '{key}' with value '{value}' was removed because of '{reason}'");
});
//You can also use .SetSlidingExpiration
varmessage="Hello "+DateTimeOffset.UtcNow.ToString();
cache.Set(CACHE_KEY,message,options);
greeting=message;
}
context.Response.Headers.Append("Content-Type","text/html");
awaitcontext.Response.WriteAsync(@"
<html>
<body>
<p>
The cache is set to expire in 5 seconds. Wait until 5 seconds then refresh this page. Check your console log to see the post eviction message event.
</p>
<p>
If you don't refresh this page, the eviction message won't be posted at the console. Here's <a href=""https://github.com/aspnet/Caching/issues/353#issuecomment-333956801"">an explanation</a> for this behavior.
</p>
</body>
</html>");
});
app.Run();