ASP.NET网站开发——数据缓存技术

数据缓存技术

缓存概念:缓存是一种在计算机中广泛用来提高性能的技术。在web应用程序的上下文中,缓存用于在Http请求间保留页或者数据,并在无需多创建的情况下多次使用它们。

目的:节省应用程序处理时间和资源

缓存体系:


@outputcache指令

Httpcachepolicy类

 protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Now.ToLongTimeString();
        }
        public static string GetTime(HttpContext conten) 
        {
            return DateTime.Now.ToLongTimeString();
        }

页面部分缓存

把@outputcache指令写入用户控件文件中


substitution控件

在使用substitution时,首先我们将整个页面缓存起来,然后将页面中需要动态改变内容的地方用substitution控件代替即可。substitution控件需要设置一个重要属性methodname,该属性用于获取或者设置当substitution控件执行时为回调而调用的方法名称。

回调方法必须要符合三点:

(1)回调方法必须定义为静态方法。

(2)方法必须接受httpcontext类型的参数。

(3)方法必须返回string类型的值。

缓存后替存



应用程序数据缓存

应用程序数据缓存的主要功能是在内存中存储各种与应用程序相关的对象,通常这些能量都需要耗费大量的服务器资源才能创建,应用程序数据缓存由cache实现。




下面是add方法

 protected void btnadd_Click(object sender, EventArgs e)
        {
            try
            {
                Cache.Add("aaa","ADD CACHE",null,Cache.NoAbsoluteExpiration,Cache.NoSlidingExpiration,CacheItemPriority.Default,null);

            }
            catch
            {
                Response.Write("ERROR");
                
            }
        }

下面是insert方法

 protected void btninsert_Click(object sender, EventArgs e)
        {
            Cache.Insert("aaa","INSERT CACHE");
        }

下面是获取get方法

protected void btnget_Click(object sender, EventArgs e)
        {
            //get
            Cache.Get("");

            //索引
            if (Cache["aaa"]!=null)
            {
                string str = (string)Cache["aaa"];
                Response.Write(str);
            }
            else
            {
                Response.Write("缓存无效!");
            }
        }

下面是网页效果




猜你喜欢

转载自blog.csdn.net/qq706352062/article/details/80015748