MemoryCache的大小设置是什么意思? [英] What do the size settings for MemoryCache mean?

查看:465
本文介绍了MemoryCache的大小设置是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器类中,我有

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中,我有

And in Startup.cs, I have

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

这些各种尺寸设置是什么意思?

What do these various size settings mean?

这是.NET Core 2.1.

This is .NET Core 2.1.

推荐答案

我能够找到一些有用的

I was able to hunt down some helpful documentation.

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

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可以作为条目数量的限制,而不是这些条目的大小.

It turns out that SizeLimit can function as the limit on the number of entries, not the size of those entries.

一个快速的示例应用程序显示SizeLimit为1,如下所示:

A quick sample app showed that with a SizeLimit of 1, the following:

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()允许您精确控制条目应占用的大小限制.例如,在下面的示例中:

In turn, SetSize() allows you to control exactly how much of your size limit an entry should take. For instance, in the following example:

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,则仅第一个条目将被成功存储.

both test1 and test2 will have been stored in the cache. But if SizeLimit is set to 2, only the first entry will be successfully stored.

这篇关于MemoryCache的大小设置是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆