欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MVC使用Memcache+Cookie解決分布式系統(tǒng)共享登錄狀態(tài)學(xué)習(xí)筆記6

 更新時(shí)間:2016年09月21日 09:12:34   作者:叫我瑋仔  
這篇文章主要介紹了MVC使用Memcache+Cookie解決分布式系統(tǒng)共享登錄狀態(tài)學(xué)習(xí)筆記,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

      為了解決單機(jī)處理的瓶頸,增強(qiáng)軟件的可用性,我們需要將軟件部署在多臺(tái)服務(wù)器上啟用多個(gè)二級(jí)子域名以頻道化的方式,根據(jù)業(yè)務(wù)功能將網(wǎng)站分布部署在獨(dú)立的服務(wù)器上,或通過負(fù)載均衡技術(shù)(如:DNS輪詢、Radware、F5、LVS等)讓多個(gè)頻道共享一組服務(wù)器。當(dāng)我們將網(wǎng)站程序分部到多臺(tái)服務(wù)器上后,由于Session受實(shí)現(xiàn)原理的局限,無法跨服務(wù)器同步更新Session,使得登錄狀態(tài)難以通過Session共享。

      我們使用MemCache+Cookie方案來解決分布式系統(tǒng)共享登錄狀態(tài)的問題。

      Memcache服務(wù)器本身就是一個(gè)Socket服務(wù)端,內(nèi)部數(shù)據(jù)采用鍵值對(duì)的形式存儲(chǔ)在服務(wù)器的內(nèi)存中,本質(zhì)就是一個(gè)大型的哈希表。數(shù)據(jù)的刪除采用惰性刪除機(jī)制。雖然Memcache并沒有提供集群功能,但是通過客戶端的驅(qū)動(dòng)程序很容易就可以實(shí)現(xiàn)Memcache的集群配置。

     先簡單介紹一下Memcache的用法

1. 下載安裝Memcache(Windows平臺(tái))

    (1)將程序解壓到磁盤任意位置

    (2)進(jìn)入cmd窗口,運(yùn)行Memcached.exe -d install安裝服務(wù),安裝后打開服務(wù)窗口查看服務(wù)是否安裝成功。

    (3)直接在服務(wù)管理中啟動(dòng)服務(wù),或者使用cmd命令 net start "Memcache Server"

    (4)使用Telnet連接到Memcache控制臺(tái),驗(yàn)證服務(wù)是否正常 telnet 127.0.0.1 11211

            使用stats指令查看當(dāng)前Memcache服務(wù)器狀態(tài)

2. 程序中的用法

    (1)在程序中添加 Memcached.ClientLibrary.dll 的引用

    (2)C#中操作Memcache的代碼示例

String[] serverlist = { "192.168.1.100:11211",
"192.168.1.101:11211" };
// initialize the pool for memcache servers
SockIOPool pool = SockIOPool.GetInstance("test");
pool.SetServers(serverlist);
pool.Initialize();
mc = new MemcacheClient();
mc.PoolName = "test";
mc.EnableCompression = false;
pool.Shutdown();//關(guān)閉連接池

下面我們做方案的具體實(shí)現(xiàn)

1. 首先在Common層中引入Memcached.ClientLibrary.dll,并封裝Memcache的幫助類,MemcacheHelper

using Memcached.ClientLibrary;
using System;

namespace PMS.Common
{
 public class MemcacheHelper
 {
 private static readonly MemcachedClient Mc = null;

 static MemcacheHelper()
 {
 //最好放在配置文件中
 string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" };

 //初始化池
 var pool = SockIOPool.GetInstance();
 pool.SetServers(serverlist);

 pool.InitConnections = 3;
 pool.MinConnections = 3;
 pool.MaxConnections = 5;

 pool.SocketConnectTimeout = 1000;
 pool.SocketTimeout = 3000;

 pool.MaintenanceSleep = 30;
 pool.Failover = true;

 pool.Nagle = false;
 pool.Initialize();

 // 獲得客戶端實(shí)例
 Mc = new MemcachedClient {EnableCompression = false};
 }
 /// <summary>
 /// 存儲(chǔ)數(shù)據(jù)
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static bool Set(string key,object value)
 {
 return Mc.Set(key, value);
 }
 public static bool Set(string key, object value,DateTime time)
 {
 return Mc.Set(key, value,time);
 }
 /// <summary>
 /// 獲取數(shù)據(jù)
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public static object Get(string key)
 {
 return Mc.Get(key);
 }
 /// <summary>
 /// 刪除
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public static bool Delete(string key)
 {
 return Mc.KeyExists(key) && Mc.Delete(key);
 }
 }
}

2. 改變用戶登錄方法UserLogin,用戶登錄成功后生成GUID,將此GUID存入Cookie并以GUID為鍵將登錄用戶信息序列化存入Memcache服務(wù)器。

public ActionResult UserLogin()
{
 #region 驗(yàn)證碼校驗(yàn)
 var validateCode = Session["validateCode"] != null ? Session["validateCode"].ToString() : string.Empty;
 if (string.IsNullOrEmpty(validateCode))
 return Content("no:驗(yàn)證碼錯(cuò)誤!!");
 Session["validateCode"] = null;
 var txtCode = Request["ValidateCode"];
 if (!validateCode.Equals(txtCode, StringComparison.InvariantCultureIgnoreCase))
 return Content("no:驗(yàn)證碼錯(cuò)誤!!");
 #endregion

 var userName = Request["UserName"];
 var userPwd = Request["PassWord"];
 //查詢用戶是否存在
 var user = UserService.LoadEntities(u => u.UserName == userName && u.PassWord == userPwd).FirstOrDefault();
 if (user == null) return Content("no:登錄失敗");

 //產(chǎn)生一個(gè)GUID值作為Memache的鍵.
 var sessionId = Guid.NewGuid().ToString();
 //將登錄用戶信息存儲(chǔ)到Memcache中。
 MemcacheHelper.Set(sessionId, SerializeHelper.SerializeToString(user), DateTime.Now.AddMinutes(20));
 //將Memcache的key以Cookie的形式返回給瀏覽器。
 Response.Cookies["sessionId"].Value = sessionId;
 return Content("ok:登錄成功");
}

3. 改變登錄校驗(yàn)控制器FilterController的OnActionExecuting方法,使其校驗(yàn)方式改為從Memcache服務(wù)器中讀取Cookie中值為鍵的對(duì)象:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
 base.OnActionExecuting(filterContext);
 //if (Session["user"] == null)
 if (Request.Cookies["sessionId"] != null)
 {
 var sessionId = Request.Cookies["sessionId"].Value;
 //根據(jù)該值查Memcache.
 var obj = MemcacheHelper.Get(sessionId);
 if (obj == null)
 {
 filterContext.Result = Redirect("/Login/Index");
 return;
 }
 var user = SerializeHelper.DeserializeToObject<User>(obj.ToString());
 LoginUser = user;
 //模擬出滑動(dòng)過期時(shí)間.
 MemcacheHelper.Set(sessionId, obj, DateTime.Now.AddMinutes(20)); 
 }
 else
 filterContext.Result = Redirect("/Login/Index");
}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論