MVC 2 - 在内存中缓存字符串
我想将数据库中的字符串缓存在内存中,这样我就不必每次都访问数据库。我尝试使用 System.Runtime.Caching,但它似乎不起作用。
在本地站点上,所有数据都会被缓存,但用户必须在辅助站点上进行身份验证。一旦用户通过身份验证,他们就会被带回本地站点,但缓存的所有数据都消失了。
有办法解决上述问题吗?以下是我的代码的一部分:
using System.Runtime.Caching;
ObjectCache cache = MemoryCache.Default;
public bool CacheIsSet(string key)
{
return cache.Contains(key);
}
public object CacheGet(string key)
{
return cache.Get(key);
}
public void CacheSet(string key, object value)
{
CacheItemPolicy policy = new CacheItemPolicy();
cache.Set(key, value, policy);
}
非常感谢。
I would like to cache strings in memory from the database so that I do not have to access the database every time. I tried using System.Runtime.Caching, but it does not seem to work.
On the local site, all the data is cached but the user has to be authenticated on a secondary site. Once the user is authenticated, they are brought back to the local site but all the data that was cached is gone.
Is there a way to fix the above issue? Below is part of my code:
using System.Runtime.Caching;
ObjectCache cache = MemoryCache.Default;
public bool CacheIsSet(string key)
{
return cache.Contains(key);
}
public object CacheGet(string key)
{
return cache.Get(key);
}
public void CacheSet(string key, object value)
{
CacheItemPolicy policy = new CacheItemPolicy();
cache.Set(key, value, policy);
}
Thanks very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该引用
HttpRuntime.Cache
对象。我围绕这个创建了一个包装器,类似于您在问题中引用的内容。请随意使用它:这是一个示例用例。函数
LoadPosts
应该加载博客文章以在网站上显示。该函数将首先查看帖子是否被缓存,如果没有,它将从数据库加载帖子,然后缓存它们:第一次运行该函数时,缓存将返回
null
,因为我们尚未向 BlogPosts 键添加任何内容。第二次调用该函数时,帖子将位于缓存中,并且if
块中的代码将不会运行,从而节省了我们访问数据库的次数。You should be referencing the
HttpRuntime.Cache
object. I created a wrapper around this, similar to what you have referenced in your question. Feel free to use it:Here is a sample use case. The function
LoadPosts
is supposed to load blog posts to display on the site. The function will first see if the posts are cached, if not it will load the posts from the database, and then cache them:The first time this function is run, the cache will return
null
, because we didn't add anything to the BlogPosts key yet. The second time the function is called the posts will be in the cache and the code in theif
block will not run, saving us a trip to the database.