在上一篇文章中咱們研究了Redis的安裝及一些基本的緩存操做,今天咱們就利用Redis緩存實現一個Session共享,基於.NET平臺的Seesion共享用的最多的應該是SQLServer數據庫實現,我以前參與的一個項目麼麼親子社區就是用的SQLSERVER實現不一樣子域名之間的Session共享。先打個廣告嘿嘿,麼麼親子網:enmuo.com,i.enmuo.com就是經過SQLSERVER實現Session共享 歡迎你們訪問。html
該片文章主要介紹主域名跟不一樣子域名之間的Session信息共享。web
糾正上一篇文章中關於RredisHelper類中的一個錯誤,就是要把設置緩存過時時間的代碼放在設置完緩存值的後面,要不當第一次給該緩存鍵賦值的時候設置的緩存時間無論用,這個我也不知道爲真麼,具體修改以下:redis
/// <summary> /// 添加單個實體到鏈表中 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="listId"></param> /// <param name="Item"></param> /// <param name="timeout"></param> public void AddEntityToList<T>(string listId, T Item, int timeout = 0) { IRedisTypedClient<T> iredisClient = Redis.As<T>(); var redisList = iredisClient.Lists[listId]; redisList.Add(Item); iredisClient.Save(); if (timeout >= 0) { if (timeout > 0) { secondsTimeOut = timeout; } Redis.Expire(listId, secondsTimeOut); }
下面咱們開始進入正題,首先介紹一下Cookie與Session的關係數據庫
咱們都知道Session是存在Server端,Cookie是存在用戶瀏覽器本地或內存中,用戶在發起一個HTTP請求時,在請求的Header中會有Cookie信息,而Cookie中有一個ASP.NET_Sessionid的值,咱們就是經過這個值獲取到服務器端對應的Session信息。以下圖所示:瀏覽器
說明:圖片中的token值是個人另外一篇博文中用到的,本篇文章中不涉及該值。緩存
下面介紹一下個人思路服務器
程序實現邏輯:cookie
一、 咱們新建一個以下項目,只用關注紅線圈住的,其餘沒有用session
二、 CookieHelper.cs文件ide
在該文件中咱們首先定義一個常量const string RedisSessionCookiesId = "RedisSessionCookiesId";做爲cookie中存儲SessionId的健。咱們用Guid.NewGuid()
生成一個惟一的值存儲在cookie中做爲SessionId的值,咱們給cookie的Domain屬性複製 "session.com",做爲共享cookie的頂級域名。
具體代碼以下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace LONG.Common { public class CookieHelper { //sessionId 的Key const string RedisSessionCookiesId = "RedisSessionCookiesId"; /// <summary> /// 獲取設置SessionID值 /// </summary> /// <returns></returns> public static string CreatSessionCookie() { if (HttpContext.Current.Request.Cookies[RedisSessionCookiesId] != null) { return HttpContext.Current.Request.Cookies[RedisSessionCookiesId].Value.ToString(); } else { Guid guid = Guid.NewGuid(); HttpCookie cokie = new HttpCookie(RedisSessionCookiesId); cokie.Value = guid.ToString(); cokie.Expires = System.DateTime.Now.AddDays(1); cokie.Domain = "session.com"; //cokie.Path = "/"; cokie.HttpOnly = true; HttpContext.Current.Response.Cookies.Add(cokie); return guid.ToString(); } } } }
三、 RredisHelper.cs文件不作介紹,詳見:http://www.cnblogs.com/lc-chenlong/archive/2013/07/26/3218157.html
四、 SessionHelper.cs 文件
經過索引器實現Session[「XX」]的取值賦值操做。對索引器不瞭解的童鞋能夠百度一下。
由於在一個項目中咱們能夠定義不少Session,好比Session[「name」]、Session[「url」]等,然而SessionID卻只有一個值,那麼咱們怎麼區分這些Session值呢,咱們能夠用SessionID+」_」+Session索引值實現,如:SessionID+」_name」、 SessionID+」_url」。
代碼以下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace LONG.Common { public class SessionHelper { public RedisHelper Redis = new RedisHelper(true); public object this[string key] { get { key = CookieHelper.CreatSessionCookie() + "_" + key; //距離過時時間還有多少秒 long l = Redis.TTL(key); return Redis.Get<object>(key); } set { SetSession(key,value); } } public void SetSession(string key,object value) { if (string.IsNullOrWhiteSpace(key)) { throw new Exception("Key is Null or Epmty"); } key = CookieHelper.CreatSessionCookie() + "_"+key; Redis.Set<object>(key, value,60*3); } public string SessionId { get { return CookieHelper.CreatSessionCookie();} } } }
對Session共享測試
一、新建兩個web項目
二、咱們在WebForm1.aspx.cs中添加以下代碼:
protected void Page_Load(object sender, EventArgs e) { test(); } public void test() { SessionHelper Session = new SessionHelper(); if (Session["user"] == null) { Session["user"] = "eric"; } //爲了展現兩個session的過時時間不同,讓線程休眠2s System.Threading.Thread.Sleep(2000); if(Session["url"]==null) { Session["url"] = "http://baidu.com"; } //Session["user"] = "qwewrwe"; string text = string.Format("session['user']的值爲:{0},距離過時時間:{1}秒", Session["user"].ToString(), Session.Redis.TTL(Session.SessionId + "_user")); text += "<br />"; text += string.Format("session['url']的值爲:{0},距離過時時間:{1}秒", Session["url"].ToString(), Session.Redis.TTL(Session.SessionId + "_url")); Response.Write(text); }
三、在Default.aspx中添加以下代碼:
public partial class _Default : System.Web.UI.Page { SessionHelper Session = new SessionHelper(); protected void Page_Load(object sender, EventArgs e) { Label1.Text= Session["user"].ToString()+"___"+Session["url"].ToString(); } protected void Button1_Click(object sender, EventArgs e) { //改變Session["user"]的值 Session["user"] = TextBox1.Text; Label1.Text = Session["user"].ToString()+"___"+Session["url"].ToString(); } }
四、我在IIS想新建了兩個項目:session.com(對應WebForm1.aspx項目)和b.session.com(對應Default.aspx項目)
五、運行session.com下過以下:
六、運行 b.session.com,咱們發現咱們獲取到session.com站點的session值
七、b.session.com在文本框中輸入」陳龍」並點擊【改變Session[user] 值】按鈕。以下圖:
八、刷新session.com發現session[‘user’]的值已經改變,並且過時時間也被刷新。
九、等到session.com 頁面session[‘url’]的過時時間爲0時刷新b.session.com
說明Session值已過時。
整個例子已經寫完,若是文中有說的不對的地方歡迎指正。
點擊下載源碼
天天學習一點點,天天進步一點點。