Asp.Net Core中的缓存介绍

一 netcore中缓存相关的类库都在 Microsoft.Extensions.Caching ,使用MemoryCache首先安装包

Install-Package Microsoft.Extensions.Caching.Memory
using Microsoft.Extensions.Caching.Memory;
using System;

namespace 应用程序缓存2
{
    class Program
    {
        static void Main(string[] args)
        {
            //缓存配置
            MemoryCacheOptions options = new MemoryCacheOptions()
            {
                SizeLimit = 100,
                CompactionPercentage = 0.2,
                ExpirationScanFrequency = TimeSpan.FromSeconds(3)
            };
            //内存缓存
            MemoryCache memoryCache = new MemoryCache(options);
            while (true)
            {
                Console.Write("请输入要缓存的值:");
                string result=Console.ReadLine();

                //单个缓存项的配置
                MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions()
                {
                    //绝对过期时间
                    AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),

                    //相对过期时间
                    //SlidingExpiration = TimeSpan.FromSeconds(3),
                    //优先级,当缓存压缩时会优先清除优先级低的缓存项
                    Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove
                                                     //缓存大小占1份
                    Size = 1
                };
                cacheEntityOps.RegisterPostEvictionCallback((key, value, reason, state) => {
                    Console.WriteLine($"回调函数输出【键:{key},值:{value},被清除的原因:{reason}】");
                });  
                //检查是否存在Name的缓存
                object cached;
                bool res= memoryCache.TryGetValue("name",out cached);
                if (!res)
                {
                    Console.WriteLine("检查到不存在缓存");
                    memoryCache.Set("name", result, cacheEntityOps);
                }
                else
                {
                    Console.WriteLine($"name缓存的结果是{cached}");
                }
                Console.ReadKey();
            }
        }
    }
}

参考 https://www.cnblogs.com/wyy1234/p/10519681.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值