using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Bowin.Common.JSON; using System.Web.Script.Serialization; using System.Configuration; namespace Bowin.Common.Cache { public class XXProvider : ICacheProvider { string XXRoot = ConfigurationManager.AppSettings["xixicache"] + "/"; private string CacheKey_Format = ConfigurationManager.AppSettings["cacheKey"] + "_{0}"; const int expire = 36000; private bool TryGet(string key, out object value) { value = null; try { Uri getUri = new Uri(XXRoot + "manager/get?k=" + key); WebRequest wq = WebRequest.Create(getUri); var r = wq.GetResponse(); var sr = r.GetResponseStream(); byte[] buffer = new byte[r.ContentLength]; sr.Read(buffer, 0, buffer.Length); //JavaScriptSerializer j = new JavaScriptSerializer(); //value = j.Deserialize(Encoding.Default.GetString(buffer), value.GetType()); //value = Encoding.Default.GetString(buffer); value = Encoding.UTF8.GetString(buffer); return true; } catch (Exception ex) { return false; } } private bool Store(string key, object value) { try { Uri setUri = new Uri(XXRoot + "manager/set?k=" + key + "&v=" + value.ToJson() + "&e=" + expire.ToString()); WebRequest wq = WebRequest.Create(setUri); var r = wq.GetResponse(); return true; } catch (Exception ex) { return false; } } private bool Delete(string key) { try { Uri setUri = new Uri(XXRoot + "manager/del?k=" + key); WebRequest wq = WebRequest.Create(setUri); var r = wq.GetResponse(); return true; } catch (Exception ex) { return false; } } public object Add(string key, object entry, DateTime utcExpiry) { object oOutObject = entry; key = string.Format(CacheKey_Format, key); if (!this.TryGet(key, out oOutObject)) { this.Store(key, entry); } return oOutObject; } public object Get(string key) { object oOutObject = null; key = string.Format(CacheKey_Format, key); this.TryGet(key, out oOutObject); return oOutObject; } public void Remove(string key) { key = string.Format(CacheKey_Format, key); this.Delete(key); } public void Set(string key, object entry, DateTime utcExpiry) { object oOutObject = entry; key = string.Format(CacheKey_Format, key); if (this.TryGet(key, out oOutObject)) { this.Store(key, entry); } else { this.Store(key, entry); } } } }