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

问题描述 投票:0回答:2

在控制器类中,我有

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。

c# caching asp.net-core-2.1 memorycache
2个回答
38
投票

我能够找到一些有用的文档

SizeLimit 没有单位。如果已设置缓存大小限制,则缓存条目必须以它们认为最合适的任何单位指定大小。缓存实例的所有用户应使用相同的单位系统。如果缓存条目大小的总和超过 SizeLimit 指定的值,则不会缓存条目。如果没有设置缓存大小限制,则条目上设置的缓存大小将被忽略。

事实证明,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");

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


0
投票

SizeLimit
表示总体积是多少?
Size
或者
SetSize
的作用是指定它需要占总体积的多少份额?

例如以下代码:

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

据说总体积等于3,根据这个总体积,在下面的代码中:

1>> cache.Set("item1", "I am ITEM 1", new MemoryCacheEntryOptions().SetSize(2));
2>> cache.Set("item2", "I am ITEM 2", new MemoryCacheEntryOptions().SetSize(2));
3>> cache.Set("item3", "I am ITEM 3", new MemoryCacheEntryOptions().SetSize(1));

在第 1 行中,我们需要在缓存中存储一些内容,它需要总可用卷 3 中的 2。由于请求的卷可用,因此将执行该操作。现在总可用量是:

3-2=1

在第 2 行中,我们再次需要在缓存中存储一些内容,它需要总可用卷 1 中的 2。由于请求的卷不可用,因此操作未执行

在第 3 行中,我们需要在缓存中存储一些内容,它需要总可用卷 1 中的 1。由于请求的卷可用,因此将执行该操作。现在总可用量是:

1-1=0

从现在开始,直到部分总卷再次被释放为止,不会缓存任何内容。

所以,在下面的代码中:

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

cache.Set("item1", "I am ITEM 1", new MemoryCacheEntryOptions().SetSize(2));
cache.Set("item2", "I am ITEM 2", new MemoryCacheEntryOptions().SetSize(2));
cache.Set("item3", "I am ITEM 3", new MemoryCacheEntryOptions().SetSize(1));

var item1 = (string)cache.Get("item1");
var item2 = (string)cache.Get("item2"); //<<! attention
var item3 = (string)cache.Get("item3");

item1
item3
将包含缓存值,但
item2
将为空;

© www.soinside.com 2019 - 2024. All rights reserved.