.NET Core 安装引用MemoryCache(Microsoft.Extensions.Caching.Memory)及使用示例代码

本文主要介绍.NET Core中,安装引用内存缓存MemoryCache(Microsoft.Extensions.Caching.Memory)的方法,以及使用它缓存数据及文件的相关的示例。

1、使用Nuget安装引用MemoryCache(Microsoft.Extensions.Caching.Memory)

1)使用Nuget界面管理器

相关文档VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package Microsoft.Extensions.Caching.Memory -Version 2.0.0

3)使用.NET CLI命令安装

> dotnet add package Microsoft.Extensions.Caching.Memory --version 2.0.0

2、使用示例代码

using System;
using System.Threading;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
namespace MemoryCacheSample
{
    public class Program
    {
        public static void Main()
        {
            //创建MemoryCache对象
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            object result;
             //获取存储缓存数据的Key
            string key = "Key";
            //存储的数据对象
            object newObject = new object();
            object state = new object();

            // 创建 / 覆盖缓存
            result = cache.Set(key, newObject);
            result = cache.Set(key, new object());
            // 获取缓存数据,没有返回null
            result = cache.Get(key);
            //out得到数据,返回是否获取成功
            bool found = cache.TryGetValue(key, out result);
            // 使用弱引用存储和获取
            result = cache.SetWeak<object>(key, newObject);
            result = cache.GetWeak<object>(key);
            // 删除缓存
            cache.Remove(key);
            // 缓存条目配置:
            // 保留在缓存中的时间越长越好
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));
            // 如果在指定时间内没有访问,则自动删除
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5)));
            // 在特定时间自动删除
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2)));
            // 在特定时间自动删除,相对于现在的UTC
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetAbsoluteExpiration(relative: TimeSpan.FromMinutes(10)));
            //如果在指定时间内没有访问,则自动删除
            //在特定时间自动删除(如果使用时间长)
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(5))
                .SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2)));
            // 收回时回调
            var options = new MemoryCacheEntryOptions()
                .RegisterPostEvictionCallback(
                (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                });
            result = cache.Set(key, new object(), options);
            // 令牌过期时删除
            var cts = new CancellationTokenSource();
            options = new MemoryCacheEntryOptions()
                .AddExpirationToken(new CancellationChangeToken(cts.Token))
                .RegisterPostEvictionCallback(
                (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                });
            result = cache.Set(key, new object(), options);
            // 触发token以查看执行的注册的回调
            cts.Cancel();
            // 如果从属条目过期,则使条目过期
            using (var entry = cache.CreateEntry("key1"))
            {
                // 如果Key值为“key2”的条目过期,则该条目过期。
                entry.Value = "value1";
                cts = new CancellationTokenSource();
                entry.RegisterPostEvictionCallback(
                    (echoKey, value, reason, substate) =>
                    {
                        Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                    });
                cache.Set("key2", "value2", new CancellationChangeToken(cts.Token));
            }
            // 触发token以查看执行的注册的回调
            cts.Cancel();
        }
    }
}

开源地址https://github.com/aspnet/Caching

推荐阅读
cjavapy编程之路首页