use*_*042 4 c# asp.net caching
我使用以下.net代码将对象添加到缓存中:
public static void Add<T>(string key, T dataToCache)
{
try
{
ApplicationLog.Instance.WriteInfoFormat("Inserting item with key {0} into Cache...", key);
HttpRuntime.Cache.Insert(
key,
dataToCache,
null,
DateTime.Now.AddDays(7),
System.Web.Caching.Cache.NoSlidingExpiration);
}
catch (Exception ex)
{
ApplicationLog.Instance.WriteException(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我从缓存中检索值的代码:
public static T Get<T>(string key)
{
try
{
if (Exists(key))
{
ApplicationLog.Instance.WriteInfoFormat("Retrieving item with key {0} from Cache...", key);
return (T)HttpRuntime.Cache[key];
}
else
{
ApplicationLog.Instance.WriteInfoFormat("Item with key {0} does not exist in Cache.", key);
return default(T);
}
}
catch(Exception ex)
{
ApplicationLog.Instance.WriteException(ex);
return default(T);
}
}
public static bool Exists(string key)
{
bool retVal = false;
try
{
retVal= HttpRuntime.Cache[key] != null;
}
catch (Exception ex)
{
ApplicationLog.Instance.WriteException(ex);
}
return retVal;
}
Run Code Online (Sandbox Code Playgroud)
但我发现每隔2分钟左右,缓存的对象值将被设置为null,从而再次从数据库中提取该值.
我在这里失踪了什么?
首先,您的访问权限不同步,因此这是一个很好的问题来源.从HttpRuntime Cache读取保证是线程安全的,因此您应该尝试读取您的项目作为每个缓存操作的第一步.
在检查是否Exists和实际检索项目之间可能发生很多事情(例如您的项目不再在那里).您应该获得正在寻找的项目的句柄,如果不是,那么通过从持久性数据存储中获取它来提供线程安全插入.
因此,您的Add逻辑将进入您的GetIF,数据不存在.提供单独的Add逻辑并没有什么根本性的错误,与阻止对特定数据的进一步请求相比,您应该多次测量数据库的成本.
T GetT(string key)
{
T item = (cache.Get(key) as T);
if (item == null)
{
lock (yourSyncRoot)
{
// double check it here
item = (cache.Get(key) as T);
if (item != null)
return item;
item = GetMyItemFromMyPersistentStore(key); // db?
if (item == null)
return null;
string[] dependencyKeys = {your, dependency, keys};
cache.Insert(key, item, new CacheDependency(null, dependencyKeys),
absoluteExpiration, slidingExpiration, priority, null);
}
}
return item;
}
Run Code Online (Sandbox Code Playgroud)
根据您的到期政策,您可以将数据存储在内存中,并提供快速和同步的访问权限,但正如我所说,测量它并根据您的需要进行调整.在更新项目并将其正确保存到持久存储之后的业务逻辑中,只需将其从缓存中删除,然后下一次调用Get将再次获取它.
| 归档时间: |
|
| 查看次数: |
13338 次 |
| 最近记录: |