在 .NET Core WebAPI 中使用分布式内存缓存时设置最大内存

Chi*_*obe 2 c# asp.net-core

我正在编写一个基于 .NET Core 的 WebAPI。我想通过在 Startup.ConfigureServices 中注册 IDistributedCache 来为我的开发环境使用分布式内存缓存。

public void ConfigureServices(IServiceCollection services)
{
    if (_hostContext.IsDevelopment())
    {
        services.AddDistributedMemoryCache();
    }
    else
    {
        services.AddDistributedRedisCache(options =>
        {
          options.Configuration = "localhost";
          options.InstanceName = "SampleInstance";
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我不希望数据缓存耗尽我的大部分 RAM。例如,如何限制 DistributedMemoryCache 仅使用 2GIG?

nla*_*ker 5

AddDistributedMemoryCache()有一个重载,允许您配置MemoryDistributedCacheOptions. 你可以做:

services.AddDistributedMemoryCache(options =>
{
   options.SizeLimit = 2000 * 1024 * 1024; // 2000MB
});
Run Code Online (Sandbox Code Playgroud)

看起来默认是200MB