.net core 缓存

.NET Core 提供了两个独立的缓存框架:一个是针对本地内存的缓存,另一个是针对分布式存储的缓存。前者可以在不经过序列化的情况下直接将对象存储在当前应用程序进程的内存中,后者则需要将对象序列化成字节数组并存储到一个独立的“中心数据库”中。对于分布式缓存,.NET Core提供了针对 Redis 和 SQL Server 的原生支持。除了这两个独立的缓存系统,ASP.NET Core还借助一个中间件实现了响应缓存(Response Caching),即按照HTTP缓存规范对整个响应内容实施缓存。

  1. 基于内存的缓存框架实现在 NuGet 包“Microsoft.Extensions.Caching.Memory”中,具体的缓存功能承载于通过 IMemoryCache 接口表示的服务对象。由于缓存的数据直接存放在内存中,并且不涉及持久化存储,所以无须考虑针对缓存对象的序列化问题,这种内存模式对缓存数据的类型也就没有任何限制。
 1 using ConsoleApp7;
 2 using Microsoft.AspNetCore.Builder;
 3 using Microsoft.Extensions.Caching.Memory;
 4 using Microsoft.Extensions.FileProviders;
 5 using Microsoft.Extensions.FileSystemGlobbing;
 6 using System.Diagnostics;
 7 
 8 Host.CreateDefaultBuilder().ConfigureWebHostDefaults(webHost =>
 9 {
10     webHost.ConfigureServices(services =>
11     {
12         services.AddMemoryCache();
13     });
14     webHost.Configure((context, config) =>
15     {
16         config.Run((httpContext) =>
17         {
18             IMemoryCache memoryCache = httpContext.RequestServices.GetService<IMemoryCache>();
19             if (!memoryCache.TryGetValue("datetime", out string time))
20             {
21                 memoryCache.Set("datetime", DateTime.Now.ToString());
22             }
23             else
24             {
25                 httpContext.Response.WriteAsync(time);
26             }
27             return Task.CompletedTask;
28         });
29     });
30 }).Build().Run();

测试结果

 

承载 Redis 分布式缓存框架的 NuGet包“Microsoft.Extensions.Caching.Redis”,我们需要手动添加针对该NuGet包的依赖。

 

 1 using Microsoft.AspNetCore.Builder;
 2 using Microsoft.Extensions.Caching.Distributed;
 3 using Microsoft.Extensions.Caching.Memory;
 4 using Microsoft.Extensions.Caching.Redis;
 5 using Microsoft.Extensions.FileProviders;
 6 using Microsoft.Extensions.FileSystemGlobbing;
 7 using System.Diagnostics;
 8 
 9 Host.CreateDefaultBuilder().ConfigureWebHostDefaults(webHost =>
10 {
11     webHost.ConfigureServices(service =>
12     {
13         service.AddDistributedRedisCache(redisCacheOptions =>
14         {
15             redisCacheOptions.InstanceName = "test";
16             redisCacheOptions.Configuration = "192.168.0.190";
17         });
18     });
19     webHost.Configure(config =>
20     {
21         config.Run(async (httpContext) =>
22         {
23             IDistributedCache distributedCache = httpContext.RequestServices.GetRequiredService<IDistributedCache>();
24             string time = await distributedCache.GetStringAsync("datetime");
25             if (time == null)
26             {
27                 await distributedCache.SetStringAsync("datetime", DateTime.Now.ToString(), new DistributedCacheEntryOptions
28                 {
29 
30                     AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60),//绝对过期时间
31                     //AbsoluteExpirationRelativeToNow = TimeSpan.Zero,
32                     SlidingExpiration = TimeSpan.FromSeconds(60),//滑动过期时间 可以续期的
33                 });
34                 distributedCache.SetString("datetime", DateTime.Now.ToString());
35             }
36             else
37             {
38                 httpContext.Response.WriteAsync(time);
39             }
40         });
41     });
42 }).Build().Run();

 

posted on 2023-02-19 20:56  是水饺不是水饺  阅读(86)  评论(0编辑  收藏  举报

导航