c# .net 程序级 缓存,可设置缓存对象的到期时间,到期后缓存key为空

115 篇文章 1 订阅
90 篇文章 7 订阅

c# .net 程序级 缓存,可设置缓存对象的到期时间,到期后缓存key为空

一、缓存帮助类

CacheHelp.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace CacheWeb
{
    public class CacheHelp
    {

        /// <summary>
        /// 缓存指定对象,设置缓存
        /// </summary>
        /// <param name="key">缓存的key</param>
        /// <param name="value">缓存的值</param>
        /// <param name="Seconds">设置缓存时间;单位:秒</param>
        /// <returns></returns>
        public static bool Set(string key, object value,double Seconds)
        {
            return Set(key, value, null, DateTime.Now.AddSeconds(Seconds), Cache.NoSlidingExpiration,
            CacheItemPriority.Default, null);
        }

        /// <summary>
        /// 缓存指定对象,设置缓存
        /// </summary>
        public static bool Set(string key, object value, string path)
        {
            try
            {
                var cacheDependency = new CacheDependency(path);
                return Set(key, value, cacheDependency);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 缓存指定对象,设置缓存
        /// </summary>
        public static bool Set(string key, object value, CacheDependency cacheDependency)
        {
            return Set(key, value, cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
            CacheItemPriority.Default, null);
        }

        /// <summary>
        /// 缓存指定对象,设置缓存
        /// </summary>
        public static bool Set(string key, object value, double seconds, bool isAbsulute)
        {
            return Set(key, value, null, (isAbsulute ? DateTime.Now.AddSeconds(seconds) : Cache.NoAbsoluteExpiration),
            (isAbsulute ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(seconds)), CacheItemPriority.Default,
            null);
        }

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        public static object Get(string key)
        {
            return GetPrivate(key);
        }

        /// <summary>
        /// 判断缓存中是否含有缓存该键
        /// </summary>
        public static bool Exists(string key)
        {
            return (GetPrivate(key) != null);
        }

        /// <summary>
        /// 移除缓存对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            HttpRuntime.Cache.Remove(key);
            return true;
        }

        /// <summary>
        /// 移除所有缓存
        /// </summary>
        /// <returns></returns>
        public static bool RemoveAll()
        {
            IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator();
            while (iDictionaryEnumerator.MoveNext())
            {
                HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key));
            }
            return true;
        }


        /// <summary>
        /// 尝试获取缓存,不存在则执行匿名委托
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="func"></param>
        /// <param name="Seconds">设置缓存时间;单位:秒</param>
        /// <returns></returns>
        public static T TryGet<T>(string key, Func<T> func, double Seconds)
        {
            if (Exists(key)) return (T)Get(key);
            var result = func.Invoke();
            Set(key, result, Seconds);
            return result;
        }


        /// <summary>
        /// 设置缓存
        /// </summary>
        public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime,
        TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
        {
            if (string.IsNullOrEmpty(key) || value == null)
            {
                return false;
            }
            HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority,
            cacheItemRemovedCallback);
            return true;
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        private static object GetPrivate(string key)
        {
            return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
        }
    }
}

二、程序使用

1、简单的数据缓存

string SetCacheStatusMsg = "初始数据";
string CacheKey = "CacheKeyTest";
string EasyCacheData = null; 
if (!CacheHelp.Exists(CacheKey))
{
	#region 增加缓存
	EasyCacheData = "测试的数据";
	bool SetCacheStatus = CacheHelp.Set(
		key: CacheKey,
		value: EasyCacheData,
		Seconds: 60 //缓存时长,单位“秒”
		);
	if (SetCacheStatus)
	{
		SetCacheStatusMsg = "增加缓存成功";
	}
	else
	{
		SetCacheStatusMsg = "增加缓存失败";
	}
	#endregion
}
else {
	#region 获取缓存
	EasyCacheData = CacheHelp.Get(CacheKey).ToString(); 
	#endregion
}
ViewBag.EasyCacheData = EasyCacheData;

2、“泛型”数据缓存

string CacheKeyUserList = "CacheKeyUserList";
List<UserInfoModel> ListCacheData = null;
if (!CacheHelp.Exists(CacheKeyUserList))
{
	#region 增加缓存

	//造数据(可以直接数据库访问获得数据)
	List<UserInfoModel> list = new List<UserInfoModel>();
	for (int i = 1; i < 6; i++)
	{
		UserInfoModel userinfo = new UserInfoModel();
		userinfo.ID = i;
		userinfo.name = "小明" + i + "号";
		list.Add(userinfo);
	}
	ListCacheData = list;



   bool SetCacheStatus = CacheHelp.Set(
		key: CacheKeyUserList,
		value: list,
		Seconds: 60 //缓存时长,单位“秒”
		);
	if (SetCacheStatus)
	{
		SetCacheStatusMsg = "增加缓存成功";
	}
	else
	{
		SetCacheStatusMsg = "增加缓存失败";
	}
	#endregion
}
else
{
	#region 获取缓存
	ListCacheData = (List<UserInfoModel>)CacheHelp.Get(CacheKeyUserList);
	#endregion
}
ViewBag.ListCacheData = ListCacheData;

三、视图使用

@using CacheWeb.Controllers;
@{

    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h3>简单的数据缓存 【EasyCacheData】</h3>
    <p class="lead"> @ViewBag.EasyCacheData </p>
 
</div>


<div class="jumbotron">
    <h3>二、“泛型”数据缓存 【ListCacheData】</h3>
    @{
        foreach (UserInfoModel item in (List<UserInfoModel>)ViewBag.ListCacheData)
        {
             <p class="lead"> ID: @item.ID | Name:@item.name</p>
        }
    } 
</div>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙-极纪元JJY.Cheng

客官,1分钱也是爱,给个赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值