Memcached是一个高性能的分布式内存对象缓存体系,用于动态Web应用以减轻数据库负载。它经由过程在内存中缓存数据和对象来削减读取数据库的次数,从而进步动态、数据库驱动网站的速率。Memcached基于一个存储键/值对的hashmap。其保卫历程(daemon )是用C写的,然则客户端能够用任何言语来编写,并经由过程memcached协定与保卫历程通讯。
我们能够运用Memcached缓存string范例等已内部完成了序列化的范例,然则关于我们自定义的范例,我们并不能在Memcached中缓存下来,由于Memcached只能缓存序列化以后的数据,因而,在这里我们将自定义的实体范例序列化一下就能够在Memcached中存储了。
起首下载windows平台下的memcached,然后装置。装置完以后就是启动memcached效劳了,你能够在cmd下用dos敕令输入,也能够在计算机治理->效劳->memcached->启动.来开启效劳.
随后就是在项目中引入相干dll:
Commons.dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll
在项目的援用中引入Memcached.ClientLibrary.dll
随后就是编写顺序了,在这里建立一个MVC顺序:
在Models文件夹中建立一个类:
[Serializable] public class VIP { public string UserName { get; set; } public int? Vip { get; set; } public DateTime? VipEndDate { get; set; } public string Mail { get; set; } public string QQ { get; set; } }
若没有标注为可序列化,则后续运转顺序将会报错。
随后建立一个MemcachedHelper类来辅佐编程.
public class MemcachedHelper { public static MemcachedClient mclient; static MemcachedHelper() { string[] serverlist = new string[] { "127.0.0.1:11211" }; SockIOPool pool = SockIOPool.GetInstance("First"); pool.SetServers(serverlist); pool.Initialize(); mclient = new MemcachedClient(); mclient.PoolName = "First"; mclient.EnableCompression = false; } public static bool set(string key, object value, DateTime expiry) { return mclient.Set(key, value, expiry); } public static object Get(string key) { return mclient.Get(key); } }
末了就是Controller内里的细致完成:
public class EntityMemcachedController : Controller { // // GET: /EntityMemcached/ /// <summary> /// 序列化实体类为字节数组,将其存储到Memcached中,以缓存数据,从而减轻接见压力.... /// </summary> /// <returns></returns> public ActionResult Index() { var vipInfo = new List<VIP>{ new VIP{ UserName="张三", Vip=1, QQ="3123456", Mail="3123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(1) }, new VIP{ UserName="李四", Vip=1, QQ="4123456", Mail="4123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(2) }, new VIP{ UserName="王五", Vip=1, QQ="5123456", Mail="5123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(3) }, new VIP{ UserName="赵六", Vip=1, QQ="6123456", Mail="6123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(4) }, new VIP{ UserName="刘七", Vip=1, QQ="7123456", Mail="7123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(5) } }; if (Request.Cookies["_EntityMemcached"] == null) { string sessionId = Guid.NewGuid().ToString(); Response.Cookies["_EntityMemcached"].Value = sessionId; Response.Cookies["_EntityMemcached"].Expires = DateTime.Now.AddMinutes(1);//设置cookie逾期时候 MemcachedHelper.set(sessionId, vipInfo, DateTime.Now.AddMinutes(1));//设置缓存逾期时候 return Content("Memcached分布式缓存设置胜利!!!"); } else { string key = Request.Cookies["_EntityMemcached"].Value.ToString(); object obj = MemcachedHelper.Get(key); List<VIP> info = obj as List<VIP>; if (info != null) { return View(info); } } return Content("若显现则有'bug'"); }
看看完成:
然后退出来,从新点击”完成memcached缓存”
我设置了一分钟以内的缓存,因而在这一分钟以内将一直是这个界面,不得不说memcached照样不错!后续接着研讨OutputCached + Monogodb的缓存战略
以上就是高性能缓存体系(Memcached)的实例引见的细致内容,更多请关注ki4网别的相干文章!