高性能緩存系統Memcached在ASP.NET MVC中應用
阿新 • • 發佈:2017-12-04
index req 緩存系統 help add nts .... ont p s
首先下載windows平臺下的memcached,然後安裝。安裝完之後就是啟動memcached服務了,你可以在cmd下用dos命令輸入,也可以在計算機管理->服務->memcached->啟動.來開啟服務.
隨後就是在項目中引入相關dll:
Commons.dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll
在項目的引用中引入Memcached.ClientLibrary.dll
隨後就是編寫程序了,在這裏創建一個MVC程序:
在Models文件夾中創建一個類:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[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類來輔助編程.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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裏面的具體實現:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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在ASP.NET MVC中應用