Build a distributed architecture using nginx + iis + redis + Task. MainForm (redis stores distributed shared sessions and Sharing session operation processes), nginxredis

Source: Internet
Author: User
Tags redis cluster

Build a distributed architecture using nginx + iis + redis + Task. MainForm (redis stores distributed shared sessions and Sharing session operation processes), nginxredis

This article is about using windows + nginx + iis + redis + Task. mainForm is used to build a distributed architecture. nginx is used on windows in the previous article. nginx is usually configured in linux when it is officially released. I will test the shared content here as a guiding role; the following describes the core nodes of the entire architecture. I hope you will like them a bit more:

 

. Architecture Design Diagram Display

. Nginx + iis build service cluster

. Redis stores distributed and shared sessions.

. Redis master-slave configuration and Sentinel management of multiple Redis Clusters

. Scheduled framework Task. MainForm provides data for redis Cluster Storage

 

The above is what I think is the core part of the entire architecture. It does not contain Database Design (please ignore it). Let's officially share today's article (Redis stores distributed and shared sessions.):

. Understand distributed sessions (personal understanding)

Analyze the distributed session Flow Process

. Encapsulate common methods for session login verification and exit

. Redis stores distributed session login instances

 

Let's share it one step at a time:

. Understand distributed sessions (personal understanding)

First, the session operation method. Here we will talk about the login session. The understanding is based on my personal opinion, and the understanding here may not be so profound; generally, the website or management system we build has user login. After login, a session storing basic user information is stored on the server. There are many ways to save the session, here we want to share with you the use of redis to store sessions. As the number of login users increases, more and more sessions are stored on the server, if a server uses the sesssion stored in memory, the memory occupation of the server will be improved, and the server may eventually crash directly. The serious cause is that the hard disk may burn out due to the memory usage of 100% for a long time, multiple storage methods are created, such as synchronizing sessions to different servers for read/write splitting and storing sessions in databases; in fact, the redis Cluster Storage operation session method we will use is mainly to share the read and write;

Second, the read/write splitting of sessions usually corresponds to a large amount of access to the site. If the access volume is so large, the release of the site should also correspond to the cluster method (namedDistributed architecture), The most obvious difference between the distributed architecture and the single-site mode is that multiple sites in the distributed architecture only need to use one of the login portals to log on, and other sites share this session, you do not need to perform the login operation again. In fact, it can be viewedSingle Sign-onOnly distributed clusters generally accessSame domain name or same ip segmentHowever, the single-site mode is usually because I have logged on to the site, and I can only use the system, but not the other system (generally speaking );

Finally, to satisfy the shared session, the session is either stored in the same place and read in the same place; you can either implement real-time synchronization to different servers or ports in redis cluster mode to implement data read/write splitting; this ensures a unified data source;

 

Analyze the distributed session Flow Process

First of all, the content above also basically introduces the distributed session (Unified session data source). Here we will talk about several questions about distributed login:

How does the system generate a shared session?

. The user obtains the same session based on the data

. Sharing session Lifecycle

Below are the answers and descriptions for the above questions:

. Session generation is actually to save session data. When a user logs on to a distributed site for the first time, the database checks the account for running logon. Before returning logon success information to the user, A unique key in a distributed system. The general rule of this key isDistributed site Id (Id corresponding to each distributed sub-site) + timestamp + unique account for user login + encrypted string + GuidCombined (there may be other different methods to ensure the unique key), and then encrypted with md5 or hash, save the basic information and key of the user to the specified Redis Service (save session with redis, usually the relationship between key-value pairs, the key is returned to the user's cookie.

. The session to which the user wants to go is to pass the key stored in the cookie to each distributed site, the site obtains the corresponding key and the data stored in the session where the specified session is read. The user can log on to the distributed system as long as the user has a valid cookie; if I use IE to log on to the system and then use google to access the system, the logon fails because the cookie does not have cross-domain access, however, if you manually or manually use the cookie key returned after the ie login is successful to google, then the same login is no problem. You can try the principle analysis and the problem is OK.

. We should be very concerned about the life cycle of a session. Generally, a session cannot be set to a wireless life cycle for a long time. At this time, we need to follow the time when each user triggers authentication login, automatically Set the session expiration time (generally, the expiration time defined by your session is pushed back after the current time). Because the cookie is used in the distributed system, you need to re-update the key expiration time of the cookie, in this way, the cookie + seesion is used to save the user's login validity until the user has exceeded the session validity period, and the login verification has not been triggered or the cookie has been cleared by special methods, at this time, the expired cookie or session will verify that the user needs to log on to access the page that requires permissions.

 

. Encapsulate common methods for session login verification and exit

First, the two C # methods to be released have been tested. You can use them directly. Of course, this method has been used in the CacheRepository cache factory discussed earlier, because the session I saved is in redis, the method content is first posted below:

1 /// <summary> 2 /// Login Extension class 3 /// </summary> 4 public class UserLoginExtend 5 {6 7 public static string HashSessionKey = "Hash_SessionIds "; 8 public static string CookieName = "Sid"; 9 10 public static T BaseSession <T> (HttpContextBase context) where T: class, new () 11 {12 // get token13 var cookie = context in the cookie. request. cookies. get (CookieName); 14 if (cookie = null) {return default (T);} 15 16/ /Use toke to query whether the cache factory has the corresponding session information. If yes, the cache factory time is automatically extended to nAddCookieExpires for 17 minutes. // return CacheRepository. current (CacheType. redisCache ). getHashValue <T> (HashSessionKey, cookie. value); 18 return CacheRepository. current (CacheType. redisCache ). getCache <T> (cookie. value); 19} 20 21 public static RedirectResult BaseCheckLogin <T> (22 HttpContextBase context, 23 out T t, 24 int nAddCookieExpires = 30, 25 string loginUrl = "/U Ser/Login ") where T: class, new () 26 {27 var returnUrl = context. request. path; 28 var result = new RedirectResult (string. format ("{0 }? ReturnUrl = {1} ", loginUrl, returnUrl); 29 t = default (T); 30 try31 {32 33 // get token34 var cookie = context in the cookie. request. cookies. get (CookieName); 35 if (cookie = null) {return result;} 36 37 // use toke to query whether the cache factory has the corresponding session information, if the cache factory time is automatically extended by nAddCookieExpires minutes 38 // t = CacheRepository. current (CacheType. redisCache ). getHashValue <T> (HashSessionKey, cookie. value); 39 t = CacheRepository. current (CacheType. R EdisCache ). getCache <T> (cookie. value, true); 40 if (t = null) 41 {42 // clear cookie43 cookie. expires = DateTime. now. addDays (-1); 44 context. response. setCookie; 45 return result; 46} 47 48 // after successful login verification, You need to reset the toke expiration time in the cookie 49 cookie. expires = DateTime. now. addMinutes (nAddCookieExpires); 50 context. response. setCookie; 51 52 // set the session expiration time 53 CacheRepository. current (CacheType. redisCache ). addExpire (Cookie. value, nAddCookieExpires); 54} 55 catch (Exception ex) 56 {57 return result; 58} 59 return null; 60} 61 62 public static RedirectResult BaseLoginOut (HttpContextBase context, string redirectUrl = "/") 63 {64 var result = new RedirectResult (string. isNullOrEmpty (redirectUrl )? "/": RedirectUrl); 65 try66 {67 // obtain token68 var cookie = context in the cookie. request. cookies. get (CookieName); 69 if (cookie = null) {return result;} 70 71 var key = cookie. value; 72 73 // set the expired cookie (first expired cookie) 74 cookie. expires = DateTime. now. addDays (-1); 75 context. response. setCookie; 76 77 // remove session78 // var isRemove = CacheRepository. current (CacheType. redisCache ). removeHashByKey (HashSessionKey, key); 79 var isRemove = CacheRepository. current (CacheType. redisCache ). remove (key); 80} 81 catch (Exception ex) 82 {83 84 throw new Exception (ex. message); 85} 86 // jump to the specified address 87 return result; 88} 89}

The BaseCheckLogin method is used to verify whether a user logs on. If the user does not log on to the redirection address, the session Validity Period of redis storage is automatically reset and the cookie validity period is reset; if you look at the code, there are remarks about the important points;

The BaseLoginOut method is mainly used to clear the session data and cookie data after the user logs out. These two methods are usually required for login verification. The two methods return RedirectResult, which is applicable to the. net mvc version;

 

. Redis stores the logon instance of the distributed session (here is the. net mvc code operation)

First, check the login action Code:

1 [HttpPost] 2 // [ValidateAntiForgeryToken] 3 public ActionResult Login ([Bind (Include = "UserName, UserPwd", Exclude = "Email")] MoUserInfo model, string returnUrl) 4 {5 6 if (ModelState. isValid) 7 {8 // initialize the database to read data nginx + iis + redis + Task. mainForm builds a distributed architecture-(nginx + iis build a service cluster) 9 model. email = "841202396@qq.com"; 10 model. id = 1; 11 model. introduce = "focused on web development for 20 years"; 12 model. sex = false; 13 model. tel = "183012787xx"; 14 model. photo = "/Content/ace-master/assets/images/avatars/profile-pic.jpg"; 15 16 model. nickName = "shiniu walking 3"; 17 model. addr = "Beijing-Yizhuang"; 18 model. birthday = "1991-05-31"; 19 model. blog =" http://www.cnblogs.com/wangrudong003/ "; 20 21 var role = new StageModel. moRole (); 22 role. name = "System Administrator"; 23 role. des = "manage the entire system"; 24 25 // obtain the corresponding menu Id based on the role Id, which is constructed in the form of List <int> 26 var menus = new List <StageModel. moMenu> {27 new StageModel. moMenu {28 Id = 1001,29 Link = "/User/UserCenter" 30}, 31 new StageModel. moMenu {32 Id = 1002,33 Link = "/User/ChangeUser1" 34}, 35 new StageModel. moMenu {36 Id = 1003,37 Link = "" 38}, 39 40 new StageModel. moMenu {41 Id = 2001001,42 Link = "" 43}, 44 new StageModel. moMenu {45 Id = 2001002,46 Link = "" 47} 48}; 49 50 // assign personal information 51 var userData = new StageModel. moUserData (); 52 userData. email = model. email; 53 userData. id = model. id; 54 userData. introduce = model. introduce; 55 userData. sex = model. sex; 56 userData. tel = model. tel; 57 userData. photo = model. photo; 58 59 userData. userName = model. userName; 60 userData. nickName = model. nickName; 61 userData. addr = model. addr; 62 userData. birthday = model. birthday; 63 userData. blog = model. blog; 64 65 // Ids 66 userData that can access the menu. menus = menus; 67 68 // obtain the unique token69 var token = CacheRepository. current (CacheType. baseCache ). getSessionId (userData. userName); 70 var timeOut = 2; // minute 71 // if (CacheRepository. current (CacheType. redisCache ). setHashCache <StageModel. moUserData> ("Hash_SessionIds", token, userData, 2) 72 if (CacheRepository. current (CacheType. redisCache ). setCache <StageModel. moUserData> (token, userData, 2, true) 73 {74 var cookie = new HttpCookie (UserLoginExtend. cookieName, token); 75 cookie. expires = DateTime. now. addMinutes (timeOut); 76 HttpContext. response. appendCookie (cookie); 77 78 return new RedirectResult (returnUrl); 79} 80} 81 82 return View (model); 83}View Code

Var token = CacheRepository is used. current (CacheType. baseCache ). getSessionId (userData. userName) method. This method is mainly used to obtain the distributed unique key mentioned above. The parameter only needs to pass the unique account that the user logs on to (the underlying layer uses the Md5hash algorithm, the code is given at the end of the text); Use CacheRepository after obtaining the key. current (CacheType. redisCache ). setCache <StageModel. moUserData> (token, userData, 2, true) method to set the basic login information to the redis service, if the redis data is successfully saved, then through HttpContext. response. appendCookie; the key is output to the user's cookie and saved;

Then, after logging on to the user's background, it usually jumps to the user's background. Some pages in the user's background need logon verification. Here I use several controllers in the background to inherit the same parent-level BaseController, in the parent class, override the Initialize method to verify the login information. The Code is as follows:

1 public class BaseController: Controller 2 {3 4 protected StageModel. moUserData userData; 5 6 protected override void Initialize (System. web. routing. requestContext requestContext) 7 {8 9 // use the Login Extension to verify the login and obtain the login information 10 var redirectResult = UserLoginExtend. baseCheckLogin (requestContext. httpContext, out userData, 2); 11 // Verification Failed, jump to loginUrl12 if (redirectResult! = Null) 13 {14 requestContext. httpContext. response. redirect (redirectResult. url, true); 15 return; 16} 17 18 // Verification Successful. Add view access login information data 19 ViewBag. userData = userData; 20 base. initialize (requestContext); 21} 22}

The BaseCheckLogin method is the public authentication login method we shared above. For specific parameters, see the parameter description. After the code is written, let's take a look at the running page effect (I am using the nginx cluster in the previous chapter for demonstration ):

In the red box, the Sid produced by Alibaba Cloud is the key mentioned above. Then, when we open a browser tab, we can see the Sid of system 02,

The login client looks at the Data graph that we saved in the redis service after logging on, as shown in:

The keys in redis are the same as those in our browser. Therefore, the content in this chapter is coming to an end. If you think this article is useful to you, please add more information"Like", Thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.