.Net Core 中 MemoryCache 使用

简介: .Net Core 中 MemoryCache 使用

1.Demo,实际项目中不这么使用

class Program
    {
        static void Main(string[] args)
        {
            //缓存的配置
            MemoryCacheOptions cacheOps = new MemoryCacheOptions()
            {
                //缓存最大为100份
                //##注意netcore中的缓存是没有单位的,缓存项和缓存的相对关系
                SizeLimit = 100,
                //缓存满了时,压缩20%(即删除20份优先级低的缓存项)
                CompactionPercentage = 0.2,
                //两秒钟查找一次过期项
                ExpirationScanFrequency = TimeSpan.FromSeconds(3)
            };
            MemoryCache myCache = new MemoryCache(cacheOps);
            //单个缓存项的配置
            MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions()
            {
                //绝对过期时间1
                //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),
                //绝对过期时间2
                //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3),
                //相对过期时间
                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}】");
            });
            myCache.Set("mykey", "myvalue", cacheEntityOps);
            Console.WriteLine($"mykey的值:{myCache.Get("mykey") ?? "mykey缓存被清除了"}");
            Console.WriteLine("------------------暂停3秒");
            Thread.Sleep(3000);
            Console.WriteLine($"mykey的值:{myCache.Get("mykey") ?? "mykey缓存被清除了"}");
            Console.ReadKey();
        }
    }
}

2. 注入(每个要用的Controller 都要构造很麻烦)

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    // Add framework services.
    services.AddMvc();
}

HomeController.cs

public class HomeController : Controller
{
    private IMemoryCache _memoryCache;
    public HomeController(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }
 
    public IActionResult Index()
    {
        string cacheKey = "key";
        string result;
        if (!_memoryCache.TryGetValue(cacheKey, out result))
        {
            result = $"LineZero{DateTime.Now}";
            _memoryCache.Set(cacheKey, result);
        }
        ViewBag.Cache = result;
        return View();
    }
}

 

protected MemoryCacheEntryOptions EntryOptions
{
    get
    {
        return new MemoryCacheEntryOptions()
        {
            //绝对过期时间1
            //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),
            //绝对过期时间2
            //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3),
            //相对过期时间
            SlidingExpiration = TimeSpan.FromSeconds(10),
            //优先级,当缓存压缩时会优先清除优先级低的缓存项
            Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove
                                             //缓存大小占1份
            Size = 1
        };
    }
}
//后面可以加 entryOptions 策略
_memoryCache.Set(cacheKey, result,entryOptions);

 

3.建个共用类

 

public class CacheCenter
{
    public static MemoryCacheProvider MemoryCacheProvider { get; set; }
    
    //.....可加其它类
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    CacheCenter.MemoryCacheProvider = new MemoryCacheProvider();
    
    // Add framework services.   
}

MemoryCacheProvider.cs

public class MemoryCacheProvider
{
    //外面可以直接调它
    public MemoryCache MemoryCache { get; set; }
    public MemoryCacheProvider()
    {
        MemoryCacheOptions cacheOps = new MemoryCacheOptions()
        {
            //缓存最大为100份
            //##注意netcore中的缓存是没有单位的,缓存项和缓存的相对关系
            SizeLimit = 100,
            //缓存满了时,压缩20%(即删除20份优先级低的缓存项)
            CompactionPercentage = 0.2,
            //3秒钟查找一次过期项
            ExpirationScanFrequency = TimeSpan.FromSeconds(3)
        };
        MemoryCache = new MemoryCache(cacheOps);
    }
    public object Get(string key)
    {
        return MemoryCache.Get(key);
    }
    public object Set(string key, int seconds)
    {
        var options = new MemoryCacheEntryOptions()
        {
            //绝对过期时间1
            //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),
            //绝对过期时间2
            //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3),
            //相对过期时间
            SlidingExpiration = TimeSpan.FromSeconds(seconds),
            //优先级,当缓存压缩时会优先清除优先级低的缓存项
            Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove
            //缓存大小占1份
            Size = 1
        };
        return MemoryCache.Set(key, options);
    }
}

 

调用

//设值
if (!CacheCenter.MemoryCacheProvider.MemoryCache.TryGetValue<string>("mykey", out string timestamp))
{    
    CacheCenter.MemoryCacheProvider.Set("mykey", DateTime.Now.ToString(), 3);
}
//其它地方取值
CacheCenter.MemoryCacheProvider.MemoryCache.Get("mykey")
目录
相关文章
|
存储 缓存
.Net Core MemoryCache
这里介绍的微软的缓存
225 0
|
存储 缓存 .NET
.NET Core 的缓存篇之MemoryCache
前言 对于缓存我们都已经很熟悉了,缓存分为很多种,浏览器缓存、试图缓存、服务器缓存、数据库缓存等等一些,那今天我们先介绍一下视图缓存和MemoryCache内存缓存的概念和用法: 视图缓存 在老的版本的MVC里面,有一种可以缓存视图的特性(OutputCache),可以保持同一个参数的请求,在N段时间内,直接从mvc的缓存中读取,不去走视图的逻辑。
2111 0
|
3月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
46 7
|
3月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
75 0
|
4月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
55 0
|
4月前
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?