C# MemoryCache的使用和封装

封装个缓存类,方便下次使用。

using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;

namespace Order.Core.API.Cache
{
    public class GlobalCache   C#有偿Q群:927860652
    {
        private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
        private static Dictionary<string,bool> keys =new Dictionary<string,bool>(); 
        public static T Get<T>(string key)
        {
            if (Cache.TryGetValue(key, out T value))
            {
                return value;
            }
            return default(T);
        }

        public static void Set<T>(string key, T value, TimeSpan slidingExpiration)
        {
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(slidingExpiration);
            Cache.Set(key, value, cacheEntryOptions);
            try
            {
                keys.Add(key, true);
            }
            catch (Exception ex)
            {

                throw new Exception("键重复\r\n"+ex.ToString());
            }
    
        }

        public static bool Exists(string key)
        {
            return Cache.TryGetValue(key, out _);
        }

        public static void Remove(string key)
        {
            Cache.Remove(key);
            keys.Remove(key);
        }

        public static void Clear()
        {
            foreach (var key in keys)
            {
                Cache.Remove(key);
            }
            keys.Clear();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值