Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Can redis replace session?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to talk to you about whether redis can replace session. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

What is Redis?

Redis is an open source log database written in ANSI C language, supports network, memory-based and persistent, Key-Value database, and provides multi-language API.

1. Comparison with other user state saving schemes

In general, the user status in development uses session or cookie, both of which have a variety of advantages and disadvantages.

Session: easy to lose in InProc mode and cause concurrency problems. If using SQLServer or SQLServer mode consumes performance

Cookie is easy to expose some user information, encryption and decryption also consumes performance.

Redis uses this solution to solve several problems.

1.Redis access speed is fast.

two。 User data is not easy to lose.

3. It is easy to support clusters when there are many users.

4. You can view online users.

5. The user can log in at one place.

6. Persistence is supported.

two。 Realization idea

1. We know that session actually saves a sessionid in cookie. Every time the user visits, the sessionid is sent to the server, and the server looks up the corresponding status data of the user through ID.

The way I deal with it here is to define a sessionid in cookie. When the program needs to get the user status, it looks up the sessionid as a key in Redis.

two。 At the same time, session allows users to recycle session without access for a certain period of time.

This function is supported by borrowing the expiration time feature of Keys in Redis, but in terms of renewal, the program needs to intercept the request to call this method (demo has an example)

Here is the code description

3.Redis call interface

First refer to the ServiceStack-related DLL.

Add a configuration in web.config, which is used to set the Redis call address. Each service is separated by [,]. The host is written in the first place.

Initialize configuration

Static Managers () {string sessionRedis= ConfigurationManager.AppSettings ["SessionRedis"]; string timeOut = ConfigurationManager.AppSettings ["SessionRedisTimeOut"]; if (string.IsNullOrEmpty (sessionRedis)) {throw new Exception ("web.config is missing configuration SessionRedis, used between each Redis, split. The first must be a host ");} 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,// "write" link pool links MaxReadPoolSize = writeReadCount,// "read" link pool links AutoStart = true});}

A delegate is written for the convenience of control.

/ / write / public F TryRedisWrite (Func doWrite) {PooledRedisClientManager prcm = new Managers () .GetClientManagers (); IRedisClient client = null Try {using (client = prcm.GetClient ()) {return doWrite (client);}} catch (RedisException) {throw new Exception ("Redis write exception. Host:" + client.Host + ", Port:" + client.Port) } finally {if (client! = null) {client.Dispose ();}

An example of a call, the other specific look at the source code

/ / store objects in the cache as Key/Value / object categories / Collection to be written public void KSet (Dictionary value) {Func fun = (IRedisClient client) = > {client.SetAll (value); return true;} TryRedisWrite (fun);}

4. Implement Session

Write a sessionid to cookie as mentioned above

/ user state management / public class Session {/ initialize / 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 }}}

The way to access the user

/ get current user information / public object Get () where TRO classwriting new () {return new RedisClient () .KGet (SessionId) } / whether the user is online / public bool IsLogin () {return new RedisClient () .KIsExist (SessionId) } / login / public void Login (T obj) where T: class,new () {new RedisClient () .KSet (SessionId, obj, new TimeSpan (0, Managers.TimeOut, 0));}

6. Renew

The default user does not access the login status of the logged-out user for more than 30 minutes, so the user has to postpone the logout time by 30 minutes for each visit.

This requires calling the renewal method of Redis

/ extension / public void KSetEntryIn (string key, TimeSpan expiresTime) {Func fun = (IRedisClient client) = > {client.ExpireEntryIn (key, expiresTime); return false;}; TryRedisWrite (fun);}

After encapsulation

/ / renew / public void Postpone () {new RedisClient () .KSetEntryIn (SessionId, new TimeSpan (0, Managers.TimeOut, 0));}

Here I use ActionFilter in MVC3 to intercept all user requests

Namespace Test {public class SessionFilterAttribute: ActionFilterAttribute {/ public override void OnActionExecuting (ActionExecutingContext filterContext) {new Session (filterContext.HttpContext) .Postpone ();}

You need to register in Global.asax

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

5. Calling mode

To make it easier to invoke the new features in 4. 0, add an extended attribute to Controller

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

Call method

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

After reading the above, do you have any further understanding of whether redis can replace session? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report