在 ASP.NET 中,Cache 类提供了一种在服务器内存中存储数据的方法,可以显著提高应用程序性能。以下是 Cache 的常规使用方法:
1. 基本缓存操作
添加缓存项
// 最简单的添加方式
Cache["key"] = "value";
// 使用 Insert 方法添加(如果已存在则替换)
Cache.Insert("key", "value");
// 带依赖项的添加
Cache.Insert("key", "value", new System.Web.Caching.CacheDependency(Server.MapPath("file.xml")));
// 带过期策略的添加
Cache.Insert("key", "value", null,
DateTime.Now.AddMinutes(30), // 绝对过期时间
System.Web.Caching.Cache.NoSlidingExpiration); // 不使用滑动过期
读取缓存项
object value = Cache["key"];
if(value != null)
{
// 使用缓存值
string cachedValue = value.ToString();
}
// 或者使用更安全的类型转换方式
string cachedString = Cache["key"] as string;
if(cachedString != null)
{
// 使用缓存字符串
}
移除缓存项
// 移除单个缓存项
Cache.Remove("key");
// 批量移除(通过前缀)
foreach(var item in Cache)
{
if(item.ToString().StartsWith("prefix_"))
{
Cache.Remove(item.ToString());
}
}
2. 高级缓存策略
滑动过期时间
// 添加缓存项,20分钟内没有被访问则自动移除
Cache.Insert("key", "value", null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(20));
缓存依赖
// 文件依赖
Cache.Insert("key", "value",
new System.Web.Caching.CacheDependency(Server.MapPath("data.xml")));
// 多个文件依赖
string[] files = new string[] { Server.MapPath("data1.xml"), Server.MapPath("data2.xml") };
Cache.Insert("key", "value", new System.Web.Caching.CacheDependency(files));
// SQL 依赖(需要配置数据库)
SqlCacheDependency sqlDep = new SqlCacheDependency("databaseName", "tableName");
Cache.Insert("key", "value", sqlDep);
缓存优先级和回调
Cache.Insert("key", "value", null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.High, // 高优先级
new CacheItemRemovedCallback(OnCacheRemove)); // 移除回调
private void OnCacheRemove(string key, object value, CacheItemRemovedReason reason)
{
// 处理缓存被移除的情况
// reason 参数说明为什么被移除(过期、依赖改变、内存不足等)
}
3. 缓存最佳实践
合理设置过期时间:根据数据更新频率设置适当的过期策略
考虑内存使用:不要缓存大量数据,可能影响服务器性能
处理缓存穿透:对于不存在的键也要缓存(如缓存null值)
使用缓存前缀:便于管理和批量清除相关缓存
考虑线程安全:当多个请求可能同时访问和修改缓存时
4. 缓存模式示例
缓存-读取模式
public string GetData()
{
string cacheKey = "data_key";
string data = Cache[cacheKey] as string;
if(data == null)
{
// 从数据库或其他数据源获取数据
data = GetDataFromDatabase();
// 将数据存入缓存
Cache.Insert(cacheKey, data, null,
DateTime.Now.AddMinutes(30),
System.Web.Caching.Cache.NoSlidingExpiration);
}
return data;
}
缓存依赖模式
public void UpdateProduct(Product product)
{
// 更新数据库
UpdateProductInDatabase(product);
// 使相关缓存失效
Cache.Remove("products_list");
Cache.Remove($"product_{product.Id}");
}
通过合理使用 ASP.NET Cache,可以显著提高应用程序性能,减少数据库访问和计算开销。