下面介绍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