asp.net mvc json数据缓存
一些虚拟主机资源给的少, 如果直接用框架缓存, 估计内存就爆了吧, 如果不用缓存, 虚拟主机自带的数据库也是限制资源的, 访问多了就直接给timeout了,
用json文件形式缓存查询出来的数据, 虽然占用一些空间, 使用一些IO, 也是比查询数据库快的, 至少不会timeout了, 不过会占用一些空间, 可是现在虚拟主机空间都不小了, 不差这一点了哈哈,
key直接作为文件名了,扩展名乱写的(*.cache)
超时时间比较用的是DateTime.Ticks, 单位是微妙, 看下面的换算吧, 在AppSetting中增加一个cache_time节点, 单位是秒
<appSettings> <!-- 缓存时间, 单位(秒) --> <add key="cache_time" value="120" /> </appSettings>
1 public class JCache 2 { 3 public static string DirPath { get; set; } 4 private static string SplitChar = "!/~/#!"; 5 /// <summary> 6 /// 缓存时间(秒) 7 /// </summary> 8 private static long CacheTime 9 { 10 get 11 { 12 return Convert.ToInt64(ConfigurationManager.AppSettings["cache_time"]) * 10000000; 13 } 14 } 15 public static T Get<T>(string key) 16 where T : class, new() 17 { 18 var filename = Path.Combine(DirPath, key + ".cache"); 19 if(!Directory.Exists(DirPath)) 20 { 21 Directory.CreateDirectory(DirPath); 22 } 23 if (!File.Exists(filename)) 24 return null; 25 var fileContent = string.Empty;// File.ReadAllText(filename, System.Text.Encoding.UTF8); 26 using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 27 { 28 fileContent = new StreamReader(fs, System.Text.Encoding.UTF8).ReadToEnd(); 29 } 30 if (string.IsNullOrEmpty(fileContent)) 31 return null; 32 if (!fileContent.Contains(SplitChar)) 33 return null; 34 var arr = fileContent.Split(new string[] { SplitChar }, StringSplitOptions.RemoveEmptyEntries); 35 try 36 { 37 var d = Convert.ToInt64(arr[0]); 38 if (DateTime.Now.Ticks - d > CacheTime) 39 return null; 40 41 var res = JsonConvert.DeserializeObject<T>(arr[1]); 42 return res; 43 } 44 catch (Exception ex) 45 { 46 return null; 47 } 48 } 49 50 public static void Set(string key, object obj) 51 { 52 if (!Directory.Exists(DirPath)) 53 { 54 Directory.CreateDirectory(DirPath); 55 } 56 var filename = Path.Combine(DirPath, key + ".cache"); 57 var d = DateTime.Now.Ticks.ToString(); 58 if (obj == null) 59 return; 60 var json = JsonConvert.SerializeObject(obj); 61 var fileContent = string.Concat(d, SplitChar, json); 62 try 63 { 64 using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) 65 { 66 new StreamWriter(fs, System.Text.Encoding.UTF8).Write(fileContent); 67 } 68 //File.WriteAllText(filename, fileContent); 69 } 70 catch (Exception ex) 71 { 72 var xx = 1; 73 } 74 } 75 }
使用方法
var cahceKey = "xxxkey"; var cache = JCache.Get<T>(cacheKey); var model = new T(); if(cache == null){ JCache.Set<T>(cacheKey, 查询出来的数据); }else{ model = cache; }