MemoryCache 的大小设置是什么意思?

What do the size settings for MemoryCache mean?

在控制器class中,我有

using Microsoft.Extensions.Caching.Memory;
private IMemoryCache _cache;
private readonly MemoryCacheEntryOptions CacheEntryOptions = new MemoryCacheEntryOptions()
    .SetSize(1)
    // Keep in cache for this time
    .SetAbsoluteExpiration(TimeSpan.FromSeconds(CacheExpiryInSeconds));

在Startup.cs中,我有

public class MyMemoryCache
    {
        public MemoryCache Cache { get; set; }
        public MyMemoryCache()
        {
            Cache = new MemoryCache(new MemoryCacheOptions
            {
                SizeLimit = 1024,
            });
        }
    }

这些不同的大小设置是什么意思?

这是 .NET Core 2.1。

我能够找到一些有用的东西 documentation

SizeLimit does not have units. Cached entries must specify size in whatever units they deem most appropriate if the cache size limit has been set. All users of a cache instance should use the same unit system. An entry will not be cached if the sum of the cached entry sizes exceeds the value specified by SizeLimit. If no cache size limit is set, the cache size set on the entry will be ignored.

事实证明,SizeLimit 可以作为条目数量的限制,而不是这些条目的大小。

一个快速示例应用显示,在 SizeLimit 为 1 的情况下,如下:

var options = new MemoryCacheEntryOptions().SetSize(1);
cache.Set("test1", "12345", options);
cache.Set("test2", "12345", options);

var test1 = (string)cache.Get("test1");
var test2 = (string)cache.Get("test2");

test2 将为空。

反过来,SetSize() 允许您准确控制一个条目应占您的大小限制的多少。例如,在以下示例中:

var cache = new MemoryCache(new MemoryCacheOptions
{
    SizeLimit = 3,
});

var options1 = new MemoryCacheEntryOptions().SetSize(1);
var options2 = new MemoryCacheEntryOptions().SetSize(2);
cache.Set("test1", "12345", options1);
cache.Set("test2", "12345", options2);

var test1 = (string)cache.Get("test1");
var test2 = (string)cache.Get("test2");

test1test2 都将存储在缓存中。但是如果SizeLimit设置为2,只有第一个条目会被成功存储。