HttpRuntime.Cache

a.在Web开发中,我们经常能够使用到缓存对象(Cache),在ASP.NET中提供了两种缓存对象,HttpContext.Current.Cache和HttpRuntime.Cache,那么他们有什么区别呢?下面简单描述一下:

    (1):HttpContext.Current.Cache 为当前Http请求获取Cache对象,通俗来说就是由于此缓存封装在了HttpContenxt中,而HttpContext只局限于Web中,所以此缓存信息只能够在Web中使用。

    (2):HttpRuntime.Cache 获取当前应用程序的Cache,通俗来说就是此缓存信息虽然被放在了System.Web命名空间下,但是非Web程序也可以使用此缓存。

----------------------------------属性介绍-----------------------------------------------------------------------------------

 HttpRuntime.Cache.Add(

 
       KeyName,//缓存名
 
       KeyValue,//要缓存的对象
 
       Dependencies,//依赖项
 
       AbsoluteExpiration,//绝对过期时间
 
       SlidingExpiration,//相对过期时间
 
       Priority,//优先级
 
       CacheItemRemovedCallback);//缓存过期回调函数
}
 
 

//
// 摘要:
// 向 System.Web.Caching.Cache 中插入具有依赖项和到期策略的对象。
//
// 参数:
// key:
// 用于引用该对象的缓存键。
//
// value:
// 要插入缓存中的对象。
//
// dependencies:
// 所插入对象的文件依赖项或缓存键依赖项。 当任何依赖项更改时,该对象即无效,并从缓存中移除。 如果没有依赖项,则此参数包含 null。
//
// absoluteExpiration:
// 所插入对象将到期并被从缓存中移除的时间。 要避免可能的本地时间问题(例如从标准时间改为夏时制),请使用 System.DateTime.UtcNow
// 而不是 System.DateTime.Now 作为此参数值。 如果使用绝对到期,则 slidingExpiration 参数必须为 System.Web.Caching.Cache.NoSlidingExpiration。
//
// slidingExpiration:
// 最后一次访问所插入对象时与该对象到期时之间的时间间隔。 如果该值等效于 20 分钟,则对象在最后一次被访问 20 分钟之后将到期并被从缓存中移除。
// 如果使用可调到期,则 absoluteExpiration 参数必须为 System.Web.Caching.Cache.NoAbsoluteExpiration。
//
// 异常:
// System.ArgumentNullException:
// key 或 value 参数为 null。
//
// System.ArgumentOutOfRangeException:
// 将 slidingExpiration 参数设置为小于 TimeSpan.Zero 或大于一年的等效值。
//
// System.ArgumentException:
// 为要添加到 Cache 中的项设置 absoluteExpiration 和 slidingExpiration 参数。
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);

---------------------------------------------------------------------------------------------

Add与Insert的不同

HttpRuntime.Cache.Add 存在相同的键会异常,返回缓存成功的对象。

HttpRuntime.Cache.Insert存在相同的键会替换原值,无返回值。

如果您希望某个缓存项目一旦放入缓存后,就不要再被修改,那么调用Add确实可以防止后来的修改操作。而调用Insert方法,则永远会覆盖已存在项。

缓存的过期时间

缓存过期时间包括:绝对过期和滑动过期。

绝对过期:到了指定时间以后便会失效。

滑动过期:在指定时间内无访问请求便失效。

实例:

绝对过期:

HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds),System.Web.Caching.Cache.NoSlidingExpiration);

滑动过期:

HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration , TimeSpan.FromSeconds(seconds));
缓存项移除优先级

// 指定 Cache 对象中存储的项的相对优先级。
public enum CacheItemPriority
{
    //  在服务器释放系统内存时,具有该优先级级别的缓存项最有可能被从缓存删除。
    Low = 1,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项比分配了 CacheItemPriority.Normal
    //  优先级的项更有可能被从缓存删除。
    BelowNormal = 2,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项很有可能被从缓存删除,
    //  其被删除的可能性仅次于具有 CacheItemPriority.Low
    //  或 CacheItemPriority.BelowNormal 优先级的那些项。这是默认选项。
    Normal = 3,

    //  缓存项优先级的默认值为 CacheItemPriority.Normal。
    Default = 3,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项被删除的可能性
    //  比分配了 CacheItemPriority.Normal 优先级的项要小。
    AboveNormal = 4,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项最不可能被从缓存删除。
    High = 5,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项将不会被自动从缓存删除。
    //  但是,具有该优先级级别的项会根据项的绝对到期时间或可调整到期时间与其他项一起被移除。
    NotRemovable = 6,
}

--------------------公共类-------------------------------------------------------------------------------------------------------------------------------------------------

/// <summary>
/// HttpRuntime Cache读取设置缓存信息封装
/// 使用描述:给缓存赋值使用HttpRuntimeCache.Set(key,value....)等参数(第三个参数可以传递文件的路径(HttpContext.Current.Server.MapPath()))
/// 读取缓存中的值使用JObject jObject=HttpRuntimeCache.Get(key) as JObject,读取到值之后就可以进行一系列判断
/// </summary>
public class HttpRuntimeCache
{
/// <summary>
/// 设置缓存过期时间,可从配置文件中读取
/// </summary>
private static double Seconds = string.IsNullOrEmpty(ConfigurationManager.AppSettings["AbsoluteExpiration"]) ? 10 : Double.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"]);

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

/// <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, CachedItemRemoveCallBack);
}

/// <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>
public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime absoluteExpiration,
TimeSpan slidingExpiration, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
{
if (string.IsNullOrEmpty(key) || value == null)
{
return false;
}
HttpRuntime.Cache.Insert(key, value, cacheDependency, absoluteExpiration, slidingExpiration, cacheItemPriority,
cacheItemRemovedCallback);
return true;
}

/// <summary>
/// 获取缓存
/// </summary>
private static object GetPrivate(string key)
{
return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
}
/// <summary>
/// 缓存到期后的回调函数,更新缓存
/// </summary>
/// <param name="key">缓存名称</param>
/// <param name="value">缓存的值</param>
/// <param name="reason">缓存到期的原因</param>
private static void CachedItemRemoveCallBack(string key, object value, CacheItemRemovedReason reason)
{
if (!Exists(key))
{
//更新缓存

}
}
}

原文地址:https://www.cnblogs.com/johnblogs/p/8665430.html