在上一篇文章中咱们研究了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值已过时。
整个例子已经写完,若是文中有说的不对的地方欢迎指正。
点击下载源码
天天学习一点点,天天进步一点点。