詳解用Redis實現Session功能_Redis

來源:互聯網
上載者:User

0.什麼是Redis

Redis是一個開源的使用ANSI C語言編寫、支援網路、可基於記憶體亦可持久化的日誌型、Key-Value資料庫,並提供多種語言的API

1.與其他使用者狀態儲存方案比較

一般開發中使用者狀態使用session或者cookie,兩種方式各種利弊。

Session:在InProc模式下容易丟失,並且引起並發問題。如果使用SQLServer或者SQLServer模式又消耗了效能

Cookie則容易將一些使用者資訊暴露,加解密同樣也消耗了效能。

Redis採用這樣的方案解決了幾個問題,

①.Redis存取速度快。

②.使用者資料不容易丟失。

③.使用者多的情況下容易支援叢集。

④.能夠查看線上使用者。

⑤.能夠實現使用者一處登入。(通過代碼實現,後續介紹)

⑥.支援持久化。(當然可能沒什麼用)

2.實現思路

1.我們知道session其實是在cookie中儲存了一個sessionid,使用者每次訪問都將sessionid發給伺服器,伺服器通過ID尋找使用者對應的狀態資料。

在這裡我的處理方式也是在cookie中定義一個sessionid,程式需要取得使用者狀態時將sessionid做為key在Redis中尋找。

2.同時session支援使用者在一定時間不訪問將session回收。

借用Redis中Keys支援到期時間的特性支援這個功能,但是在續期方面需要程式自行攔截請求調用這個方法(demo有例子)

下面開始代碼說明 

3.Redis調用介面

首先引用ServiceStack相關DLL。

在web.config添加配置,這個配置用來設定Redis調用地址每台服務用【,】隔開。主機寫在第一位 

 <appSettings>   <!--每台Redis之間用,分割.第一個必須為主機-->  <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,每台Redis之間用,分割.第一個必須為主機");      }      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,//“寫”連結池連結數        MaxReadPoolSize = writeReadCount,//“讀”連結池連結數        AutoStart = true      });    }

 為了控制方便寫了一個委託

 /// <summary>    /// 寫入    /// </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寫入異常.Host:" + client.Host + ",Port:" + client.Port);      }      finally      {        if (client != null)        {          client.Dispose();        }      }    }

 一個調用的例子其他的具體看源碼

   /// <summary>    /// 以Key/Value的形式儲存物件到緩衝中    /// </summary>    /// <typeparam name="T">物件類別</typeparam>    /// <param name="value">要寫入的集合</param>    public void KSet(Dictionary<string, T> value)    {      Func<IRedisClient, bool> fun = (IRedisClient client) =>      {        client.SetAll<T>(value);        return true;      };      TryRedisWrite(fun);    }

4.實現Session

按上面說的給cookie寫一個sessionid

  /// <summary>  /// 使用者狀態管理  /// </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>    /// 擷取目前使用者資訊    /// </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.續期

預設使用者沒訪問超過30分鐘登出使用者的登入狀態,所以使用者每次訪問都要將使用者的登出時間延遲30分鐘

這需要調用Redis的續期方法 

 

    /// <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>/// 續期/// </summary>public void Postpone(){new RedisClient<object>().KSetEntryIn(SessionId, new TimeSpan(0, Managers.TimeOut, 0));}

這裡我利用了MVC3中的ActionFilter,攔截使用者的所有請求

namespace Test{  public class SessionFilterAttribute : ActionFilterAttribute  {    /// <summary>    /// 每次請求都續期    /// </summary>    /// <param name="filterContext"></param>    public override void OnActionExecuting(ActionExecutingContext filterContext)    {      new Session(filterContext.HttpContext).Postpone();    }  }}

在Global.asax中要註冊一下

public static void RegisterGlobalFilters(GlobalFilterCollection filters)    {      filters.Add(new SessionFilterAttribute());    }    protected void Application_Start()    {      RegisterGlobalFilters(GlobalFilters.Filters);    } 

 5.調用方式

為了方便調用借用4.0中的新特性,把Controller添加一個擴充屬性 

public static class ExtSessions{public static Session SessionExt(this Controller controller)  {    return new Session(controller.HttpContext);  }}

調用方法

  public class HomeController : Controller  {    public ActionResult Index()    {      this.SessionExt().IsLogin();      return View();    }  }

6.代碼下載

點擊下載

7.後續

SessionManager包含 擷取使用者列表數量,登出某個使用者,根據使用者ID擷取使用者資訊,線上使用者物件列表,線上使用者SessionId列表等方法

後續將實現使用者一處登入功能

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.