欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解用Redis實(shí)現(xiàn)Session功能

 更新時(shí)間:2016年12月07日 15:24:34   作者:Jlins  
本篇文章主要介紹了用Redis實(shí)現(xiàn)Session功能,具有一定的參考價(jià)值,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。

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.代碼下載

點(diǎn)擊下載

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)文章

  • 詳解SSH框架和Redis的整合

    詳解SSH框架和Redis的整合

    本篇文章主要介紹了SSH框架和Redis的整合,詳細(xì)的介紹了Struts+Spring+Hibernate和Redis整合,有興趣的可以了解一下。
    2017-03-03
  • 詳解Redis中的List類(lèi)型

    詳解Redis中的List類(lèi)型

    這篇文章主要介紹了Redis中的List類(lèi)型,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • redis數(shù)據(jù)結(jié)構(gòu)之intset的實(shí)例詳解

    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-09
  • Redis+Caffeine實(shí)現(xiàn)多級(jí)緩存的步驟

    Redis+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)題

    今天小編就為大家分享一篇解決redis修改requirepass后不生效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • 詳解Redis如何優(yōu)雅地實(shí)現(xiàn)接口防刷

    詳解Redis如何優(yōu)雅地實(shí)現(xiàn)接口防刷

    這篇文章主要為大家詳細(xì)介紹了Redis優(yōu)雅地實(shí)現(xiàn)接口防刷的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • 一文弄懂Redis 線程模型

    一文弄懂Redis 線程模型

    使用Redis 時(shí),幾乎不存在 CPU 成為瓶頸的情況, Redis 主要受限于內(nèi)存和網(wǎng)絡(luò) 使用了單線程后,可維護(hù)性高,感興趣的可以了解一下
    2024-02-02
  • 詳解Centos7下配置Redis并開(kāi)機(jī)自啟動(dòng)

    詳解Centos7下配置Redis并開(kāi)機(jī)自啟動(dòng)

    本篇文章主要介紹了Centos7下配置Redis并開(kāi)機(jī)自啟動(dòng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2016-11-11
  • redis 查看所有的key方式

    redis 查看所有的key方式

    這篇文章主要介紹了redis 查看所有的key方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-05-05
  • 一篇吃透Redis緩存穿透、雪崩、擊穿問(wèn)題

    一篇吃透Redis緩存穿透、雪崩、擊穿問(wèn)題

    這篇文主要介紹了Redis緩存穿透,緩存雪崩,緩存擊穿的問(wèn)題解決方法,文中有詳細(xì)的圖文介紹,對(duì)大家了解Redis有一定的幫助,需要的朋友可以參考下
    2023-05-05

最新評(píng)論