一些虚拟主机资源给的少, 如果直接用框架缓存, 估计内存就爆了吧, 如果不用缓存, 虚拟主机自带的数据库也是限制资源的, 访问多了就直接给timeout了,
用json文件形式缓存查询出来的数据, 虽然占用一些空间, 使用一些IO, 也是比查询数据库快的, 至少不会timeout了, 不过会占用一些空间, 可是现在虚拟主机空间都不小了, 不差这一点了哈哈,
key直接作为文件名了,扩展名乱写的(*.cache)
超时时间比较用的是DateTime.Ticks, 单位是微妙, 看下面的换算吧, 在AppSetting中增加一个cache_time节点, 单位是秒
<appSettings>
<!-- 缓存时间, 单位(秒) -->
<add key="cache_time" value="120" />
</appSettings>
public class JCache
{
public static string DirPath { get; set; }
private static string SplitChar = "!/~/#!";
/// <summary>
/// 缓存时间(秒)
/// </summary>
private static long CacheTime
{
get
{
return Convert.ToInt64(ConfigurationManager.AppSettings["cache_time"]) * ;
}
}
public static T Get<T>(string key)
where T : class, new()
{
var filename = Path.Combine(DirPath, key + ".cache");
if(!Directory.Exists(DirPath))
{
Directory.CreateDirectory(DirPath);
}
if (!File.Exists(filename))
return null;
var fileContent = string.Empty;// File.ReadAllText(filename, System.Text.Encoding.UTF8);
using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fileContent = new StreamReader(fs, System.Text.Encoding.UTF8).ReadToEnd();
}
if (string.IsNullOrEmpty(fileContent))
return null;
if (!fileContent.Contains(SplitChar))
return null;
var arr = fileContent.Split(new string[] { SplitChar }, StringSplitOptions.RemoveEmptyEntries);
try
{
var d = Convert.ToInt64(arr[]);
if (DateTime.Now.Ticks - d > CacheTime)
return null; var res = JsonConvert.DeserializeObject<T>(arr[]);
return res;
}
catch (Exception ex)
{
return null;
}
} public static void Set(string key, object obj)
{
if (!Directory.Exists(DirPath))
{
Directory.CreateDirectory(DirPath);
}
var filename = Path.Combine(DirPath, key + ".cache");
var d = DateTime.Now.Ticks.ToString();
if (obj == null)
return;
var json = JsonConvert.SerializeObject(obj);
var fileContent = string.Concat(d, SplitChar, json);
try
{
using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
new StreamWriter(fs, System.Text.Encoding.UTF8).Write(fileContent);
}
//File.WriteAllText(filename, fileContent);
}
catch (Exception ex)
{
var xx = ;
}
}
}
使用方法
var cahceKey = "xxxkey";
var cache = JCache.Get<T>(cacheKey); var model = new T();
if(cache == null){
JCache.Set<T>(cacheKey, 查询出来的数据);
}else{
model = cache;
}