詳解用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.與其他用戶狀態(tài)保存方案比較
一般開(kāi)發(fā)中用戶狀態(tài)使用session或者cookie,兩種方式各種利弊。
Session:在InProc模式下容易丟失,并且引起并發(fā)問(wèn)題。如果使用SQLServer或者SQLServer模式又消耗了性能
Cookie則容易將一些用戶信息暴露,加解密同樣也消耗了性能。
Redis采用這樣的方案解決了幾個(gè)問(wèn)題,
①.Redis存取速度快。
②.用戶數(shù)據(jù)不容易丟失。
③.用戶多的情況下容易支持集群。
④.能夠查看在線用戶。
⑤.能夠?qū)崿F(xiàn)用戶一處登錄。(通過(guò)代碼實(shí)現(xiàn),后續(xù)介紹)
⑥.支持持久化。(當(dāng)然可能沒(méi)什么用)
2.實(shí)現(xiàn)思路
1.我們知道session其實(shí)是在cookie中保存了一個(gè)sessionid,用戶每次訪問(wèn)都將sessionid發(fā)給服務(wù)器,服務(wù)器通過(guò)ID查找用戶對(duì)應(yīng)的狀態(tài)數(shù)據(jù)。
在這里我的處理方式也是在cookie中定義一個(gè)sessionid,程序需要取得用戶狀態(tài)時(shí)將sessionid做為key在Redis中查找。
2.同時(shí)session支持用戶在一定時(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ì)象類別</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>
/// 用戶狀態(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;
}
}
}
去存取用戶的方法
/// <summary>
/// 獲取當(dāng)前用戶信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public object Get<T>() where T:class,new()
{
return new RedisClient<T>().KGet(SessionId);
}
/// <summary>
/// 用戶是否在線
/// </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)用戶沒(méi)訪問(wèn)超過(guò)30分鐘注銷用戶的登錄狀態(tài),所以用戶每次訪問(wèn)都要將用戶的注銷時(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,攔截用戶的所有請(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包含 獲取用戶列表數(shù)量,注銷某個(gè)用戶,根據(jù)用戶ID獲取用戶信息,在線用戶對(duì)象列表,在線用戶SessionId列表等方法
后續(xù)將實(shí)現(xiàn)用戶一處登錄功能
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Redis實(shí)現(xiàn)雙加密Token的示例代碼
在現(xiàn)代分布式系統(tǒng)中,Token管理是身份驗(yàn)證和授權(quán)的核心部分,本文將深入分析一個(gè)基于Redis的Token管理實(shí)現(xiàn),探討其設(shè)計(jì)思路、關(guān)鍵代碼邏輯以及實(shí)現(xiàn)細(xì)節(jié),通過(guò)對(duì)源碼的逐層剖析,幫助讀者更好地理解Token管理的實(shí)現(xiàn)原理,需要的朋友可以參考下2025-01-01
分布式利器redis及redisson的延遲隊(duì)列實(shí)踐
這篇文章為大家主要介紹了分布式利器redis及redisson的延遲隊(duì)列實(shí)踐,搜遍全網(wǎng)好像還沒(méi)有使用redisson的延遲隊(duì)列的,redisson作為一個(gè)分布式利器,這么好用的工具沒(méi)人用有點(diǎn)可惜2022-03-03
Redis 中的布隆過(guò)濾器的實(shí)現(xiàn)
這篇文章主要介紹了Redis 中的布隆過(guò)濾器的實(shí)現(xiàn),詳細(xì)的介紹了什么是布隆過(guò)濾器以及如何實(shí)現(xiàn),非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-10-10
spring?boot集成redis基礎(chǔ)入門實(shí)例詳解
redis在spring?boot項(xiàng)目開(kāi)發(fā)中是常用的緩存套件,常見(jiàn)使用的是spring-boot-starter-data-redis,這篇文章主要介紹了spring?boot集成redis基礎(chǔ)入門,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10
解析redis hash應(yīng)用場(chǎng)景和常用命令
這篇文章主要介紹了redis hash應(yīng)用場(chǎng)景和常用命令,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08

