asp.net数据缓存

下面介绍asp.net一些缓存方法。
(1)页面直接缓存<%@OutputCache Duration="120"VaryByParam="*" %>

(2)页面启用缓存,当参数变化页面的缓存消失,

<%@ OutputCache Duration="120"VaryByParam="bigId;smallId;time;win;flag"%>

(3)通过save 值 get值达到用程序控制目的

        ///<summary>

        ///获取当前应用程序指定CacheKey的Cache值

        ///</summary>

        ///<param name="CacheKey"></param>

        ///<returns></returns>

        public static object GetCache(string CacheKey)

        {

            System.Web.Caching.Cache objCache =HttpRuntime.Cache;

            return objCache[CacheKey];

 

        }

 

///<summary>

        ///设置当前应用程序指定CacheKey的Cache值

        ///</summary>

        ///<param name="CacheKey"></param>

        ///<param name="objObject"></param>

        public static void SetCache(string CacheKey,object objObject, DateTime absoluteExpiration,TimeSpan slidingExpiration)

        {

            System.Web.Caching.Cache objCache =HttpRuntime.Cache;

            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);

        }

 

具体的实例为:

 

if (!IsPostBack)

        {

            if (CacheHelper.GetCache("TTask") !=null && AFRequest.GetQueryString("time") !="")

            {

                TTakes = (List<TList>)CacheHelper.GetCache("TTask");

            }

            else if (CacheHelper.GetCache("TSTask") !=null && AFRequest.GetQueryString("win") =="sovle")

            {

                TTakes = (List<TList>)CacheHelper.GetCache("TSTask");

            }

            else

            {

                IList<T_task> ttas = getList();

                bind(ttas);

            }

 

public void bind(IList<T_task> ttas)//绑定

    {

        List<TList> tls =new List<TList>();

        //查询缓存

        foreach (T_task ttain ttas)

        {

            TList tl = new TList();

            tl.Id = tta.ID.ToString();

            tl.Titel = tta.Titel;

 

            DateTime ov = Convert.ToDateTime(tta.OverTime); //期望结束

            DateTime litime = Convert.ToDateTime(tta.LimitTime);

 

            if (!tta.IsDeleting)

                tl.Tasking = "任务审核中";

 

            if (litime.CompareTo(DateTime.Now) > 0)

            {

                TimeSpan ts = litime -DateTime.Now;

                TimeSpan tss = ov -DateTime.Now;

                if (tss.Days < 1)//期望时间已结束,不让威客发布

                {

                    tl.Shenyu = "已超时" + (Funs.StrDateDiffHours(litime.ToString(), 0) / 24).ToString() +"天";

                    tl.Tasking = "任务已超时";

                }

                else

                {

                    tl.Shenyu = "" + ts.Days.ToString() +"天" + ts.Hours.ToString() +"小时" + ts.Minutes.ToString() +"分";

                    if (tta.IsDeleting)

                        tl.Tasking = "任务进行中";

                    if (tta.IsWin && tta.LastReplyUserID !="")

                        tl.Tasking = "任务结束";

                }

            }

            else

            {

                continue; //不添加

            }

 

            object tu = blltask.ScalarTableFiled("t_user","UserName", " where Uid=" + tta.UserID);

            if (tu != null)

                tl.UserID = "<a href=\"" +AFRequest.SiteUrl + "/userInfo.aspx?UserID=" + tta.UserID + "\">" + tu.ToString() +"</a>";

            else

                tl.UserID = "<font color=\"red\">没有用户名</font>";         

 

            tl.Reward = tta.Reward.ToString();

            tl.Canyu = blltask.GetRepalyNum(tta.ID, false);

            tl.Jiaogao = blltask.GetRepalyNum(tta.ID, true);

 

            object oo = blltask.IsData("t_trade","where TaskID=" + tta.ID + " and OrderFlag = 'TRADE_SUCCESS '");

            tl.TradeType = oo != null && oo.ToString() !="0" ? "已托管" :"未托管";

            tls.Add(tl);

        }

        if (AFRequest.GetQueryString("time") !="")

        {

            CommonMethods.CacheHelper.SetCache("TTask", tls,DateTime.Now.AddHours(1), TimeSpan.Zero);

            TTakes = tls;

        }

        else if (AFRequest.GetQueryString("win") =="sovle")

        {

            CommonMethods.CacheHelper.SetCache("TSTask", tls,DateTime.Now.AddHours(1), TimeSpan.Zero);

            TTakes = tls;

        }

        else

        {

            TTakes = tls;

        }

        RepDataBind(TTakes);

 

    }

(4)用html的meta完成缓存页面。如

<meta http-equiv="pragma" content="cache">

(5)使用IhttpModule

重写一个Url,让它由4部分组成:页面路径信息 + 分隔符 + 参数列表 + Url后缀

另外用户访问的时候就直接读取目录里的文件.

public void Init(HttpApplication context)

        {

            context.BeginRequest += newEventHandler(this.context_BeginRequest);

        }

 

 

   private void context_BeginRequest(object sender, EventArgs e)

        {

            HttpContext context = ((HttpApplication)sender).Context;

            if (context.Request.AppRelativeCurrentExecutionFilePath.ToLower().EndsWith(".aspx"))

            {

 

                string fileUrl = "~/CacheFile/";

                HttpRequest Req;

                Req = context.Request;

                string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);

                if (Req.ApplicationPath ==null || Req.ApplicationPath == "/")

                {

                    //直接安装在  Web   站点  

                    string[] arr =HttpContext.Current.Request.FilePath.Split('/');

                    if (arr.Length > 2)

                    {

                        fileUrl = "~/" + arr[1] +"/";

                    }

                }

                else

                {

                    //安装在虚拟子目录下  

                    //AppPath = UrlAuthority + Req.ApplicationPath;

                    string[] arr =HttpContext.Current.Request.FilePath.Split('/');

                    if (arr.Length > 3)

                    {

                        fileUrl = "~/" + arr[2] +"/";

                    }

 

                }

 

                string fileName = GetFileName(context);            

                string filePath = context.Server.MapPath(fileUrl) + fileName;

                if (File.Exists(filePath) && (DateTime.Compare(File.GetLastWriteTime(filePath).AddDays(1.0),DateTime.Now) > 0))

                {

                    context.RewritePath(fileUrl + fileName, false);

                }

    

取出该文件

public staticstring GetFileName(HttpContext context)

        {

            HttpRequest Req;

            Req = context.Request;

            string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);

            if (Req.ApplicationPath ==null || Req.ApplicationPath == "/")

            {

                //直接安装在  Web   站点                  

                string[] arr = HttpContext.Current.Request.FilePath.Split('/');

                if (arr.Length > 2)

                {

                    return (arr[2].ToLower().Replace(".aspx","") + context.Request.Url.Query.Replace("?","__").Replace("&","_").Replace("/","").Replace(@"\","") + ".html");

                }

                return (context.Request.AppRelativeCurrentExecutionFilePath.ToLower().Replace(".aspx","").Replace("~/","") + context.Request.Url.Query.Replace("?","__").Replace("&","_").Replace("/","").Replace(@"\","") + ".html");

 

            }

            else

            {

                //安装在虚拟子目录下                

                string[] arr = HttpContext.Current.Request.FilePath.Split('/');

                if (arr.Length > 3)

                {

                    return (arr[3].ToLower() + context.Request.Url.Query.Replace("?","__").Replace("&","_").Replace("/","").Replace(@"\","") + ".html");

                }

                else

                    return (context.Request.AppRelativeCurrentExecutionFilePath.ToLower().Replace(".aspx","").Replace("~/","") + context.Request.Url.Query.Replace("?","__").Replace("&","_").Replace("/","").Replace(@"\","") + ".html");

            }

        }

(6)对首页缓存的最佳方案,是生成静态。
  public class StaticFileCachePageBase : Page

    {

        protected override void Render(HtmlTextWriter writer)

        {

            StringWriter sw = new StringWriter();

            HtmlTextWriter htmlw =new HtmlTextWriter(sw);

            base.Render(htmlw);

            htmlw.Flush();

            htmlw.Close();

            string pageContent = sw.ToString();

            if (newConfig().isCache == "0")

            {

                base.Response.Write(pageContent);

            }

            else

            {

                string path = base.Server.MapPath("~/CacheFile/");           

                HttpContext HttpCurrent =HttpContext.Current;

                HttpRequest Req;

                if (HttpCurrent !=null)

                {

                    Req = HttpCurrent.Request;

 

                    string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);

                    if (Req.ApplicationPath ==null || Req.ApplicationPath == "/")

                    {

                        //直接安装在  Web   站点  

                       // AppPath = UrlAuthority;

                        string[] arr =HttpContext.Current.Request.FilePath.Split('/');

                        if (arr.Length > 2)// 对子目录下生效

                        {

                            path = base.Server.MapPath("~/" + arr[1] +"/");

                        }

 

                    }

                    else

                    {

                        //安装在虚拟子目录下  

                        //AppPath = UrlAuthority + Req.ApplicationPath;

                        string[] arr =HttpContext.Current.Request.FilePath.Split('/');

                        if (arr.Length > 2)// 对子目录下生效

                        {

                            path = base.Server.MapPath("~/" + arr[2] +"/");

                        }

 

                    }

                }              

                if (!Directory.Exists(path))

                {

                    Directory.CreateDirectory(path);

                }

 

                string pageUrl = StaticFileCacheModule.GetFileName(HttpContext.Current);

 

                Encoding code =Encoding.GetEncoding("UTF-8");

                using (StreamWriter stringWriter =new StreamWriter(path + pageUrl,false, code))

                {

                    stringWriter.Write(pageContent);

                }

                base.Response.Write(pageContent);

            }

        }

    }

     

然后首页如下,就能实现生成静态

public partialclass yugioh_index  :StaticFileCachePageBase

 案例源代码下载

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值