我在ASP.NET MVC中有一个新闻站点,其中所有数据都来自数据库的主页。这会给我的托管服务器带来大量流量。
我有以下会议:政治,体育,世界等,每个会话都是对数据库的不同请求。但每个请求只从数据库返回少量数据,最多8个结果用于查询。总共有21个对数据库的请求。
我考虑制作一个data.json文件并将会话信息保存在此文件中并在前端显示它们。
但是作为文件data.json而不是数据库,我必须完成所有工作,以便在执行删除或编辑操作时重新定位信息。
考虑到该网站已经发布,有没有更好的方法来达到我想要的目的?
答案 0 :(得分:0)
我会在站点和数据库之间放置一个缓存层,所以当你对db执行其中一个调用时,它首先会检查缓存以查看对象是否在那里,如果是,那么它会从内存中返回它们(超快),如果没有它从db获取并填充下一次缓存。当数据库中的数据发生变化时,您必须记住清除缓存。
缓存接口:
public interface ICacheProvider
{
void Add(string key, object value);
void Add(string key, object value, TimeSpan timeout);
object Get(string key);
object this[string key] { get; set; }
bool Remove(string key);
bool Contains(string key);
void ClearAll();
}
缓存实施:
public class HttpCacheProvider : ICacheProvider
{
/// <summary>
/// The http cache
/// </summary>
private readonly Cache _cache;
/// <summary>
/// How often to expire the cache
/// </summary>
public int CacheExpiryMinutes { get; set; }
public HttpCacheProvider()
: this(HttpContext.Current.Cache, 60)
{
}
public HttpCacheProvider(int cacheExpiryMinutes)
: this(HttpContext.Current.Cache, cacheExpiryMinutes)
{
}
public HttpCacheProvider(Cache cache, int cacheExpiryMinutes)
{
_cache = cache;
CacheExpiryMinutes = cacheExpiryMinutes;
}
public void Add(string key, object value)
{
if (_cache[key] == null)
_cache.Insert(key, value, null, DateTime.Now.AddMinutes(CacheExpiryMinutes), Cache.NoSlidingExpiration);
}
public void Add(string key, object value, TimeSpan timeout)
{
if (_cache[key] == null)
_cache.Insert(key, value, null, DateTime.Now.Add(timeout), Cache.NoSlidingExpiration);
}
public object Get(string key)
{
return _cache[key];
}
public bool Contains(string key)
{
return (this[key] != null);
}
public object this[string key]
{
get { return _cache[key]; }
set { _cache[key] = value; }
}
public bool Remove(string key)
{
return _cache.Remove(key) != null;
}
public void ClearAll()
{
var enumerator = _cache.GetEnumerator();
while (enumerator.MoveNext())
{
_cache.Remove(enumerator.Key.ToString());
}
}
}
用法:
private ICacheProvider _cacheProvider;
public IEnumerable<Something> GetData(int param1, int param2)
{
var cacheKey = string.Format("{0}-{1}", param1, param2);
if (!_cacheProvider.Contains(cacheKey))
{
try
{
// get data from db
// add that data to cahce
_cacheProvider.Add(cacheKey, nodes);
}
catch (Exception ex)
{
// blah, logging
}
}
return _cacheProvider[cacheKey] as IEnumerable<Something>;
}