Cache缓存对象缓存对象

Cache缓存对象缓存对象_第1张图片

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DemoCache.aspx.cs" Inherits="WebApplication1.DemoCache" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>title>
head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Cache存数据" 
            onclick="Button1_Click" />
        <asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
        <br />
        <asp:Button ID="Button2" runat="server" Text="取值" onclick="Button2_Click" />
        <br />
        <asp:Button ID="Button3" runat="server" Text="查看活动商品" onclick="Button3_Click" />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        asp:GridView>
    div>
    form>
body>
html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    public partial class DemoCache : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Cache缓存对象 
            //Cache数据是公共的,存放在服务器内容中,可以设置过期或依赖项过期(如:改变文件时过期)
            string n = TextBox1.Text;
            //Cache.Insert("appName", n, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);//绝对到期
            Cache.Insert("appName", n, null,System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));//多少时间后过期
            Response.Write("OK");
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //Cache 在使用的时候,有自动锁,所有没有Lock与unLock方法
            object obj = Cache["appName"];
            if (obj!=null)
            {
                Response.Write("名称为"+obj);
            }

        }
        //查看商品
        protected void Button3_Click(object sender, EventArgs e)
        {
            //将缓存数据呈现不通过访问数据库的方式
            if (Cache["data"] != null)
            {
                DataTable d = Cache["data"] as DataTable;
                GridView1.DataSource = d;
                GridView1.DataBind();
            }
            else
            {
                BindList();
            }
        }

        private void BindList()
        {
            string sql = "select * from student";
            DataTable dt = SQLHelper.GetTable(sql);
            //将数据放到缓存中,减少服务器压力
            Cache.Insert("data", dt, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

 

转载于:https://www.cnblogs.com/xiaz/p/5242749.html

你可能感兴趣的:(Cache缓存对象缓存对象)