添加 Cache[Key]=object  or Cache.Insert

移除 Cache.Remove(key)

1、将值直接写入Cache

代码如下 复制代码
HttpContext.Current.Cache["One"] = "1";

使用'绝对过期'方式处理缓存,过期时间为:9999年12月31日 (不推荐使用该方法处理缓存,并且应在适当的时候清空缓存Key)

2、使用Insert(String, Object)插入Cache

代码如下 复制代码
string cacheKey = "Two";
object cacheValue = HttpContext.Current.Cache.Get(cacheKey);

if(cacheValue == null)
{
    cacheValue = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

HttpContext.Current.Cache.Insert(cacheKey, cacheValue);
}

//显示指定缓存的Key 与 Value
this.ShowMessage(cacheKey, cacheValue.ToString());

3、使用Insert(String, Object, CacheDependency, DateTime, TimeSpan)插入Cache

代码如下 复制代码
string cacheKey = "__cache__students";

DataSet dataSet = this.Cache.Get(cacheKey) as DataSet;

if(dataSet == null)
{
    dataSet = new DataSet();

//加载XML并填充至DataSet
    dataSet.ReadXml(this.Server.MapPath(@"XMLFile.xml"));

//加入缓存,并设定'绝对过期时间'为5分钟
    this.Cache.Insert(cacheKey, dataSet, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
}

//绑定DataGrid数据
grdDefault.DataSource = dataSet;
grdDefault.DataBind();

该方法较重要的两个参数为absoluteExpiration及slidingExpiration
absoluteExpiration  DateTime类型,代表绝对过期时间
slidingExpiration  TimeSpan类型,代表滑动过期时间
absoluteExpiration与slidingExpiration不能同时使用
例如:设定了absoluteExpiration参数时,slidingExpiration必须设定为System.Web.Caching.Cache.NoSlidingExpiration
反之:设定了slidingExpiration参数时,absoluteExpiration必须设定为System.Web.Caching.Cache.NoAbsoluteExpiration

4、使用Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority,

更多详细内容请查看:http://www.111cn.net/net/net/56762.htm

CacheItemRemovedCallback)插入Cache

public partial class PriorityAndCallbackDemo : System.Web.UI.Page
{
    #region 静态字段
    static bool CacheItemRemoved = false;
    static CacheItemRemovedReason Reason;
    static string CacheItemKey = "fw__cache__students";
    #endregion

#region 事件处理
    //页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        //缓存项已移除
        if(PriorityAndCallbackDemo.CacheItemRemoved)
        {
            ltMessage.Text = string.Format("Key={0}已从缓存移出,原因为:{1}", PriorityAndCallbackDemo.CacheItemKey, PriorityAndCallbackDemo.Reason.ToString());
        }
    }

//'添加缓存'按钮 点击事件 处理
    protected void btnAddCache_Click(object sender, EventArgs e)
    {
        DataSet dataSet = this.Cache.Get(PriorityAndCallbackDemo.CacheItemKey) as DataSet;

if(dataSet == null)
        {
            dataSet = new DataSet();
            dataSet.ReadXml(this.Server.MapPath(@"XMLFile.xml"));

//使用 Web.config 作为缓存过期依赖项
            CacheDependency dependency = new CacheDependency(this.Server.MapPath(@"Web.config"), DateTime.Now);

//加入缓存,设定优先级为默认级别
            this.Cache.Insert(PriorityAndCallbackDemo.CacheItemKey, dataSet, dependency, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(this.CacheItemRemovedHandler));
        }

//绑定GridView数据
        grdDefault.DataSource = dataSet;
        grdDefault.DataBind();
    }

//'移除缓存'按钮 点击事件 处理
    protected void btnRemoveCache_Click(object sender, EventArgs e)
    {
        if(this.Cache[PriorityAndCallbackDemo.CacheItemKey] != null)
        {
            this.Cache.Remove(PriorityAndCallbackDemo.CacheItemKey);
        }
    }
    #endregion

#region 私有方法
    //缓存项移除事件处理
    private void CacheItemRemovedHandler(string key, object value, CacheItemRemovedReason relason)
    {
        PriorityAndCallbackDemo.CacheItemRemoved = true;
        PriorityAndCallbackDemo.Reason = relason;
    }
    #endregion
}

该方法较重要的两个参数为CacheItemPriority及CacheItemRemovedCallback
CacheItemPriority  缓存项优先级,当服务器内存不够时,优先级越高的项越不容易被移除
CacheItemRemovedCallback  该参数为委托类型,当缓存项被移除时所调用,包含Reason参数用于表示缓存项被移除的原因

【我是怎么用的】

首先理解缓存策略。可调过期策略 和 绝对过期策略。注意,两则不能同时使用

使用可调过期策略,需要将absoluteExpiration=DateTime.MaxValue ,TimeSpan .FromMinutes(10)设置项目只有在10分钟内不被使用才会被移除

代码如下 复制代码
Cache.Insert("data", "123", null , DateTime.MaxValue, TimeSpan.FromMinutes(10));

绝对策略,如天气报告,将信息保存60分钟

代码如下 复制代码
Cache.Insert("data", "123", null , DateTime.Now.AddMinutes(60), TimeSpan.Zero);

缓存依赖。

即一个缓存的失效依赖另外一个object。这里的object可以指另外一个缓存,或者一个文件,或者....

类:CacheDependency 命名空间 System.Web.Caching.CacheDependency依赖于其它缓存项目

代码如下 复制代码
System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency (null, new string [] { "time" });
Cache.Insert( "number", ++num, cacheDependency);
 
依赖于文件或文件夹
 
System.Web.Caching. CacheDependency cacheDependency = new System.Web.Caching.CacheDependency ( "test.xml");
当test.xml文件删除、更新时自动从缓存中移除
 
System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency(null, new string[] { "time" });
Cache.Insert("test", "123", cacheDependency);

移除项目回调
 Cache.Insert("test", "123", null , DateTime.Now.AddSeconds(10), TimeSpan.Zero, new CacheItemUpdateCallback(Test));
 
 
 private void Test(string key, CacheItemUpdateReason reason, out object expensiveObject, out CacheDependency dependency, out DateTime absoluteExpiration, out TimeSpan slidingExpiration)
    {
 
    }

ASP.NET缓存 Cache之数据缓存的更多相关文章

  1. MVC-Cache-1.输出缓存(Cache:[1].输出缓存2.应用程序缓存)

    缓存前提概念: 1.使用缓存的目的就是为提供网站性能,减轻对数据库的压力,提高访问的速度. 2.如果使用缓存不当,比不使用缓存造成的影响更恶劣(缓存数据的更新不及时.缓存过多等). 3..net MV ...

  2. 我用ASP.NET缓存之SQL数据缓存依赖(SqlCacheDependency)

    [名词解释] 缓存(Cache)依赖,大白话解释就是缓存是否更新依赖于其它Object.那么SqlCacheDependency指的就是Cache的数据更新依赖于SQL Server数据库表的变化(  ...

  3. [.net 面向对象程序设计进阶] (15) 缓存(Cache)(二) 利用缓存提升程序性能

    [.net 面向对象程序设计进阶] (15) 缓存(Cache)(二) 利用缓存提升程序性能 本节导读: 上节说了缓存是以空间来换取时间的技术,介绍了客户端缓存和两种常用服务器缓布,本节主要介绍一种. ...

  4. [.net 面向对象程序设计进阶] (14) 缓存(Cache) (一) 认识缓存技术

    [.net 面向对象程序设计进阶] (14) 缓存(Cache)(一) 认识缓存技术 本节导读: 缓存(Cache)是一种用空间换时间的技术,在.NET程序设计中合理利用,可以极大的提高程序的运行效率 ...

  5. web开发人员须知的web缓存知识–将数据缓存到浏览器端Net实现

    现实中,服务器在向浏览器发送的数据中,一部分数据是不经常更新的,如果能将这部分数据缓存到浏览器端,将会大大降低传输的数据,提高应用的性能.通过Expires策略,可以使用HTTP 协议定义的缓存机制将 ...

  6. cache应用(asp.net 2.0 SQL数据缓存依赖 [SqlCacheDependency ] )

    Asp.net 2.0 提供了一个新的数据缓存功能,就是利用sql server2005 的异步通知功能来实现缓存 1.首先在sqlserver2005 中创建一个test的数据库. 在SQL Ser ...

  7. mybatis源码分析(7)-----缓存Cache(一级缓存,二级缓存)

    写在前面  MyBatis 提供查询缓存,用于减轻数据库压力,提高数据库性能. MyBatis缓存分为一级缓存和二级缓存. 通过对于Executor 的设计.也可以发现MyBatis的缓存机制(采用模 ...

  8. MVC-Cache-2.应用程序缓存(Cache:1.输出缓存[2].应用程序缓存)

    2.应用数据缓存-Cache 1.引入CacheHelper.cs CacheHelper.cs文件源码在下面; 2.介绍用法: //键 string ips = "键"; //值 ...

  9. echarts图形报表缓存问题(option数据缓存)

    这几天我在工作中用到了echarts开发报表.每次查询出来的数据都是新的,但是echart展现的图形报表却还是之前的数据.网上找了搜索了很多次也没能解决,后面加了技术群才解决的. 我开始已经确定是报表 ...

随机推荐

  1. shared_ptr注意事项

    对shared_ptr的Copy构造和Copy赋值,会改变引用计数,但是对shared_ptr中原始资源的Copy构造和Copy赋值,不会改变引用计数.因此存在下面的危险情况: 1.获取资源时,初始化 ...

  2. 【开发实例】C#调用SAPI实现语音合成的两种方法

    我们都知道现在的语音合成TTS是可以通过微软的SAPI实现的,好处我就不多说了,方便而已,因为在微软的操作系统里面就自带了这个玩意,主要的方式有两种:  1.使用COM组件技术,不管是C++,C#,D ...

  3. 一步步学Mybatis-告别繁琐的配置之Mybatis配置文件生成工具 (7)

    今年是2013年的杀青之日,前几天由于比较忙,没有及时更新本篇的最后一篇东西,前六篇中我们主要都是采用手动配置相关的Mybatis映射文件与相应的接口类与实体类.当然如果在真正的使用过程中,由于业务的 ...

  4. C语言统计一个字符串中单词的个数

    假定每一个单词用空格隔开. 样例: 输入:how are you! 输出:3 两种方法: 一: #include <stdio.h> #include <string.h> # ...

  5. TP函数

    U方法用于完成对URL地址的组装,特点在于可以自动根据当前的URL模式和设置生成对应的URL地址,格式为:U('地址','参数','伪静态','是否跳转','显示域名');在模板中使用U方法而不是固定 ...

  6. [CSS] Introduction to CSS Columns

    Learn how to use CSS columns to quickly lay out fluid columns that are responsive, degrade gracefull ...

  7. poj 1222 EXTENDED LIGHTS OUT(位运算+枚举)

    http://poj.org/problem?id=1222 题意:给一个确定的5*6放入矩阵.每一个格子都有一个开关和一盏灯,0表示灯没亮,1表示灯亮着.让你输出一个5*6的矩阵ans[i][j], ...

  8. iOS开发——UI篇Swift篇&玩转UItableView(二)高级功能

    UItableView高级功能 class UITableViewControllerAF: UIViewController, UITableViewDataSource, UITableViewD ...

  9. cocos2d-x在android下的编译

    $(call import-add-path,E:/cocos2d-2.0-x-2.0.3) include $(BUILD_SHARED_LIBRARY) http://www.cnblogs.co ...

  10. Topology: The Architecture of Distributed Systems--reference

    reference:http://blog.couchbase.com/topology-architecture-distributed-systems You can’t judge a book ...