0

当我启动和停止网站/调试时如何保留 IMemorycache?我的印象是 IMemorycache 存储在服务器上,不受网站启动的影响。每次我启动和停止网站时,IMemorycache 条目都会被重置为 0 cache.Set("entryA", "data1", cacheEntryOptions); 第一次在配置中调用此行时,我希望在执行代码行后缓存中有一个条目。下次在 5 秒/分钟内或到期时间之前,如果我重新启动网站(调用启动。或停止并开始调试),即使在代码行执行之前,缓存中也应该有一个条目。但这不是它的工作方式。我的理解不正确吗?我需要一种方法将一个项目在服务器上保存至少 20 分钟,而不会在每次调用启动时丢失。

我看到了类似的帖子,但不确定标记的答案是如何解决的。在 Program.cs vc configure 中这样做有什么好处。 IMemoryCache 在应用程序启动时不保存数据

这是我们的代码

using Microsoft.Extensions.Caching.Memory;
     public Startup(IHostingEnvironment env)
            {
                const string ENV_VARIABLE_SITENAME = "%WEBSITE_SITE_NAME%";
                var siteName = Environment.ExpandEnvironmentVariables(ENV_VARIABLE_SITENAME);
    
                if (string.IsNullOrEmpty(siteName) || siteName == ENV_VARIABLE_SITENAME)
                    siteName = System.Environment.MachineName;
    
                log.Info($"*******Site Name: '{siteName}' ************");
    
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{siteName}.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();
    
                Configuration = builder.Build();
                MyConfiguration = new class.Configuration(Configuration);
            }
    
    
           public void Configure(
                                IApplicationBuilder app,
                                IHostingEnvironment env,
                                ILoggerFactory loggerFactory,
                                IMemoryCache cache
                            )
                    {
                        if (env.IsDevelopment())
                        {
                            app.UseDeveloperExceptionPage();
                            // Use Swagger
                            //app = SwaggerServiceExtensions.UseSwaggerDocumentation(app);
                        }
                        else
                        {
                            //app.UseExceptionHandler("/Error");
                            app.UseHsts();
                        }
            
                        var cacheEntryOptions = new MemoryCacheEntryOptions()
                            .SetSize(1)//Size amount
                            //Priority on removing when reaching size limit (memory pressure)
                            .SetPriority(CacheItemPriority.High)
                            // Keep in cache for this time, reset time if accessed.
                            .SetSlidingExpiration(TimeSpan.FromMinutes(5))
                            // Remove from cache after this time, regardless of sliding expiration
                            .SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
            
                        cache.Set("entryA", "data1", cacheEntryOptions);
                        
                        app.ConfigureExceptionHandler();
            
                        // Use Swagger
                        app = SwaggerServiceExtensions.UseSwaggerDocumentation(app);
            
            
                        }
            
            
            public void ConfigureServices(IServiceCollection services)
                    {
                        // for HttpContext
                        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            
                        // need MVC
                        services.AddMvc(options =>
                        {
                            options.Filters.Add(new ErrorHandlingFilter());
                        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            
                        // Memory Cache
                        services.AddMemoryCache();
        }
4

1 回答 1

1

好吧,那是一个纯内存缓存,它不是独立的实现,它只是在您的代码中运行的代码。

而且您似乎对依赖注入的工作原理有一个基本的误解。Afaik 内存缓存只会在第一次注入时实现,而不是在调用“services.AddMemoryCache()”时实现。事实上,缓存已经准备好了,当它存在时,并且 - 通过实现 - 它总是会作为 MemoryCache 类的 100% 新实例出现 - 所以在 Startup() 被调用的那一刻,里面不可能有所有东西,并且应用程序(重新)启动时正在调用启动。您实际寻找的是持久缓存解决方案,而不是纯粹的内存缓存。

你可以做什么:

  1. 最简单的解决方案:例如将 IDistributedCache 与 SQL 一起使用。那是一种将键/值对存储在数据库中的解决方案,因此是持久的(但也可以在内存中,如果您使用所谓的内存优化表),我以这种方式在 SQL 上运行一个 50 GB 的大数据库,并且甚至可以在 1 秒内查询结果(通过具有 REST 开销和所有内容的互联网)。

  2. 在自己的小应用程序上实现 Mem Cache,添加一个简单的 get/set REST API 来访问它......这样缓存就独立于您当前开发的应用程序 - 但是,同样的问题......默认的 IMemoryCache 不是那样的东西意味着持久化,缓存将始终必须在应用程序启动后手动更新。

  3. 切换到持久缓存解决方案...例如 REDIS、MemCached 等,但与 NET 提供的 DB 选项中的简单 DistributedCache 相比,这是一项完全不同的任务。

于 2021-12-31T00:02:57.543 回答