动态页面 有办法缓存起来没? 比如:网站的首页 Default.aspx 运行一次需要大量的计算 、大量的读取数据库 ,我想把 Default.aspx 运行一次之后缓存起来,然后 定时的去更新缓存,之前考虑用生成静态网页的方法,但是太繁琐了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Caching;
using System.Collections;
public static class CacheHelper
{
private static Cache _cache;
public static double SaveTime;
static CacheHelper()
{
_cache = HostingEnvironment.Cache;
SaveTime = 60;
}
public static object Get(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
return _cache.Get(key);
}
public static T Get<T>(string key)
{
object obj = Get(key);
return obj == null ? default(T) : (T)obj;
}
public static void Insert(string key, object value, CacheDependency dependency, CacheItemPriority priority, CacheItemRemovedCallback callback)
{
_cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(SaveTime), priority, callback);
}
public static void Insert(string key, object value, CacheDependency dependency, CacheItemRemovedCallback callback)
{
Insert(key, value, dependency, CacheItemPriority.Default, callback);
}
public static void Insert(string key, object value, CacheDependency dependency)
{
Insert(key, value, dependency, CacheItemPriority.Default, null);
}
public static void Insert(string key, object value)
{
Insert(key, value, null, CacheItemPriority.Default, null);
}
public static void Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return;
}
_cache.Remove(key);
}
public static IList<string> GetKeys()
{
List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = _cache.GetEnumerator();
while (enumerator.MoveNext())
{
keys.Add(enumerator.Key.ToString());
}
return keys.AsReadOnly();
}
public static void RemoveAll()
{
IList<string> keys = GetKeys();
foreach (string key in keys)
{
_cache.Remove(key);
}
}
}
插入缓存 CacheHelper.Insert("huanchun", object);
间接性缓存
有 输出缓存 OutputCache
不建议缓存整个页面,建议缓存控件,自定义缓存依赖项
要想快 使用页面缓存 方便快捷
使用数据缓存 灵活性大 不管是否使用页面缓存,最好都应该使用数据缓存,特别是常用数据
依赖缓存。