ASP.NET CORE CACHE的使用(含MemoryCache,Redis)

本文介绍了如何在ASP.NET CORE中使用MemoryCache和Redis进行缓存操作。通过定义`CacheUntity`工具类,提供统一的缓存操作接口`ICacheHelper`,并实现两个具体的缓存助手类`RedisCacheHelper`和`MemoryCacheHelper`,实现了缓存的存在检查、获取、设置和删除功能。示例代码中展示了如何在控制器中切换和使用这两种缓存方式。
摘要由CSDN通过智能技术生成

依赖命名空间:

Microsoft.AspNetCore.Mvc;//测试调用时

Microsoft.Extensions.Caching.Memory;

Microsoft.Extensions.Caching.Redis;

StackExchange.Redis;

Newtonsoft.Json;


定义通用工具类 :CacheUntity

    public class CacheUntity
    {
        private static ICacheHelper _cache = new RedisCacheHelper();//默认使用Redis


        private static bool isInited = false;
        public static void Init(ICacheHelper cache)
        {
            if (isInited)
                return;
            _cache.Dispose();
            _cache = cache;
            isInited = true;
        }


        public static bool Exists(string key)
        {
            return _cache.Exists(key);
        }


        public static T GetCache<T>(string key) where T : class
        {
            return _cache.GetCache<T>(key);
        }


        public static void SetCache(string key, object value)
        {
            _cache.SetCache(key, value);
        }


        public static void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)
        {
            _cache.SetCache(key, value, expiressAbsoulte);
        }


        //public void SetCache(string key, object value, double expirationMinute)
        //{


        //}


        public static void RemoveCache(string key)
        {
            _cache.RemoveCache(key);
        }


    }


定义统一缓存操作接口:ICacheHelper

public interface ICacheHelper
    {
        bool Exists(string key);


        T GetCache<T>(string key) where T : class;


        void SetCache(string key, object value);


        void SetCache(string key, object value, DateTimeOffset expiressAbso

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值