詳解用Redis實(shí)現(xiàn)Session功能
0.什么是Redis
Redis是一個(gè)開(kāi)源的使用ANSI C語(yǔ)言編寫(xiě)、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫(kù),并提供多種語(yǔ)言的API
1.與其他用戶(hù)狀態(tài)保存方案比較
一般開(kāi)發(fā)中用戶(hù)狀態(tài)使用session或者cookie,兩種方式各種利弊。
Session:在InProc模式下容易丟失,并且引起并發(fā)問(wèn)題。如果使用SQLServer或者SQLServer模式又消耗了性能
Cookie則容易將一些用戶(hù)信息暴露,加解密同樣也消耗了性能。
Redis采用這樣的方案解決了幾個(gè)問(wèn)題,
①.Redis存取速度快。
②.用戶(hù)數(shù)據(jù)不容易丟失。
③.用戶(hù)多的情況下容易支持集群。
④.能夠查看在線用戶(hù)。
⑤.能夠?qū)崿F(xiàn)用戶(hù)一處登錄。(通過(guò)代碼實(shí)現(xiàn),后續(xù)介紹)
⑥.支持持久化。(當(dāng)然可能沒(méi)什么用)
2.實(shí)現(xiàn)思路
1.我們知道session其實(shí)是在cookie中保存了一個(gè)sessionid,用戶(hù)每次訪問(wèn)都將sessionid發(fā)給服務(wù)器,服務(wù)器通過(guò)ID查找用戶(hù)對(duì)應(yīng)的狀態(tài)數(shù)據(jù)。
在這里我的處理方式也是在cookie中定義一個(gè)sessionid,程序需要取得用戶(hù)狀態(tài)時(shí)將sessionid做為key在Redis中查找。
2.同時(shí)session支持用戶(hù)在一定時(shí)間不訪問(wèn)將session回收。
借用Redis中Keys支持過(guò)期時(shí)間的特性支持這個(gè)功能,但是在續(xù)期方面需要程序自行攔截請(qǐng)求調(diào)用這個(gè)方法(demo有例子)
下面開(kāi)始代碼說(shuō)明
3.Redis調(diào)用接口
首先引用ServiceStack相關(guān)DLL。
在web.config添加配置,這個(gè)配置用來(lái)設(shè)置Redis調(diào)用地址每臺(tái)服務(wù)用【,】隔開(kāi)。主機(jī)寫(xiě)在第一位
<appSettings> <!--每臺(tái)Redis之間用,分割.第一個(gè)必須為主機(jī)--> <add key="SessionRedis" value="127.0.0.1:6384,127.0.0.1:6384"/> </appSettings>
初始化配置
static Managers() { string sessionRedis= ConfigurationManager.AppSettings["SessionRedis"]; string timeOut = ConfigurationManager.AppSettings["SessionRedisTimeOut"]; if (string.IsNullOrEmpty(sessionRedis)) { throw new Exception("web.config 缺少配置SessionRedis,每臺(tái)Redis之間用,分割.第一個(gè)必須為主機(jī)"); } if (string.IsNullOrEmpty(timeOut)==false) { TimeOut = Convert.ToInt32(timeOut); } var host = sessionRedis.Split(char.Parse(",")); var writeHost = new string[] { host[0] }; var readHosts = host.Skip(1).ToArray(); ClientManagers = new PooledRedisClientManager(writeHost, readHosts, new RedisClientManagerConfig { MaxWritePoolSize = writeReadCount,//“寫(xiě)”鏈接池鏈接數(shù) MaxReadPoolSize = writeReadCount,//“讀”鏈接池鏈接數(shù) AutoStart = true }); }
為了控制方便寫(xiě)了一個(gè)委托
/// <summary> /// 寫(xiě)入 /// </summary> /// <typeparam name="F"></typeparam> /// <param name="doWrite"></param> /// <returns></returns> public F TryRedisWrite<F>(Func<IRedisClient, F> doWrite) { PooledRedisClientManager prcm = new Managers().GetClientManagers(); IRedisClient client = null; try { using (client = prcm.GetClient()) { return doWrite(client); } } catch (RedisException) { throw new Exception("Redis寫(xiě)入異常.Host:" + client.Host + ",Port:" + client.Port); } finally { if (client != null) { client.Dispose(); } } }
一個(gè)調(diào)用的例子其他的具體看源碼
/// <summary> /// 以Key/Value的形式存儲(chǔ)對(duì)象到緩存中 /// </summary> /// <typeparam name="T">對(duì)象類(lèi)別</typeparam> /// <param name="value">要寫(xiě)入的集合</param> public void KSet(Dictionary<string, T> value) { Func<IRedisClient, bool> fun = (IRedisClient client) => { client.SetAll<T>(value); return true; }; TryRedisWrite(fun); }
4.實(shí)現(xiàn)Session
按上面說(shuō)的給cookie寫(xiě)一個(gè)sessionid
/// <summary> /// 用戶(hù)狀態(tài)管理 /// </summary> public class Session { /// <summary> /// 初始化 /// </summary> /// <param name="_context"></param> public Session(HttpContextBase _context) { var context = _context; var cookie = context.Request.Cookies.Get(SessionName); if (cookie == null || string.IsNullOrEmpty(cookie.Value)) { SessionId = NewGuid(); context.Response.Cookies.Add(new HttpCookie(SessionName, SessionId)); context.Request.Cookies.Add(new HttpCookie(SessionName, SessionId)); } else { SessionId = cookie.Value; } } }
去存取用戶(hù)的方法
/// <summary> /// 獲取當(dāng)前用戶(hù)信息 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public object Get<T>() where T:class,new() { return new RedisClient<T>().KGet(SessionId); } /// <summary> /// 用戶(hù)是否在線 /// </summary> /// <returns></returns> public bool IsLogin() { return new RedisClient<object>().KIsExist(SessionId); } /// <summary> /// 登錄 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> public void Login<T>(T obj) where T : class,new() { new RedisClient<T>().KSet(SessionId, obj, new TimeSpan(0, Managers.TimeOut, 0)); }
6.續(xù)期
默認(rèn)用戶(hù)沒(méi)訪問(wèn)超過(guò)30分鐘注銷(xiāo)用戶(hù)的登錄狀態(tài),所以用戶(hù)每次訪問(wèn)都要將用戶(hù)的注銷(xiāo)時(shí)間推遲30分鐘
這需要調(diào)用Redis的續(xù)期方法
/// <summary> /// 延期 /// </summary> /// <param name="key"></param> /// <param name="expiresTime"></param> public void KSetEntryIn(string key, TimeSpan expiresTime) { Func<IRedisClient, bool> fun = (IRedisClient client) => { client.ExpireEntryIn(key, expiresTime); return false; }; TryRedisWrite(fun); }
封裝以后 /// <summary> /// 續(xù)期 /// </summary> public void Postpone() { new RedisClient<object>().KSetEntryIn(SessionId, new TimeSpan(0, Managers.TimeOut, 0)); }
這里我利用了MVC3中的ActionFilter,攔截用戶(hù)的所有請(qǐng)求
namespace Test { public class SessionFilterAttribute : ActionFilterAttribute { /// <summary> /// 每次請(qǐng)求都續(xù)期 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { new Session(filterContext.HttpContext).Postpone(); } } }
在Global.asax中要注冊(cè)一下
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new SessionFilterAttribute()); } protected void Application_Start() { RegisterGlobalFilters(GlobalFilters.Filters); }
5.調(diào)用方式
為了方便調(diào)用借用4.0中的新特性,把Controller添加一個(gè)擴(kuò)展屬性
public static class ExtSessions {public static Session SessionExt(this Controller controller) { return new Session(controller.HttpContext); } }
調(diào)用方法
public class HomeController : Controller { public ActionResult Index() { this.SessionExt().IsLogin(); return View(); } }
6.代碼下載
7.后續(xù)
SessionManager包含 獲取用戶(hù)列表數(shù)量,注銷(xiāo)某個(gè)用戶(hù),根據(jù)用戶(hù)ID獲取用戶(hù)信息,在線用戶(hù)對(duì)象列表,在線用戶(hù)SessionId列表等方法
后續(xù)將實(shí)現(xiàn)用戶(hù)一處登錄功能
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
redis數(shù)據(jù)結(jié)構(gòu)之intset的實(shí)例詳解
這篇文章主要介紹了redis數(shù)據(jù)結(jié)構(gòu)之intset的實(shí)例詳解的相關(guān)資料, intset也即整數(shù)集合,當(dāng)集合保存的值數(shù)量不多時(shí),redis使用intset作為其底層數(shù)據(jù)保存結(jié)構(gòu),希望通過(guò)本文能幫助到大家,需要的朋友可以參考下2017-09-09Redis+Caffeine實(shí)現(xiàn)多級(jí)緩存的步驟
隨著不斷的發(fā)展,這一架構(gòu)也產(chǎn)生了改進(jìn),在一些場(chǎng)景下可能單純使用Redis類(lèi)的遠(yuǎn)程緩存已經(jīng)不夠了,還需要進(jìn)一步配合本地緩存使用,例如Guava cache或Caffeine,從而再次提升程序的響應(yīng)速度與服務(wù)性能,這篇文章主要介紹了Redis+Caffeine實(shí)現(xiàn)多級(jí)緩存,需要的朋友可以參考下2024-01-01解決redis修改requirepass后不生效的問(wèn)題
今天小編就為大家分享一篇解決redis修改requirepass后不生效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05詳解Redis如何優(yōu)雅地實(shí)現(xiàn)接口防刷
這篇文章主要為大家詳細(xì)介紹了Redis優(yōu)雅地實(shí)現(xiàn)接口防刷的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03詳解Centos7下配置Redis并開(kāi)機(jī)自啟動(dòng)
本篇文章主要介紹了Centos7下配置Redis并開(kāi)機(jī)自啟動(dòng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-11-11