当我启动和停止网站/调试时如何保留 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();
}