1. 程式人生 > >用Redis實現Session功能,實現單點登入

用Redis實現Session功能,實現單點登入

0.什麼是Redis

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

---維基百科

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

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

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

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

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

1.Redis存取速度快。

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

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

4.能夠檢視線上使用者。

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

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

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呼叫地址每臺服務用【,】隔開。主機寫在第一位

1 <appSettings>
2 
3     <!--每臺Redis之間用,分割.第一個必須為主機-->
4     <add key="SessionRedis" value="127.0.0.1:6384,127.0.0.1:6384"/>
5 
6 </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列表等方法

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


<script type="text/javascript"><!-- google_ad_client = "ca-pub-1944176156128447"; /* cnblogs 首頁橫幅 */ google_ad_slot = "5419468456"; google_ad_width = 728; google_ad_height = 90; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>