[MVC study notes] 6. Use Memcache+cookie to resolve distributed system shared login status

Source: Internet
Author: User
Tags memcached

In order to solve the bottleneck of single machine processing and enhance the usability of software, we need to deploy software on multiple servers to enable multiple level two subdomains to be deployed on separate servers based on business functions, or through load balancing techniques such as DNS polling, radware, F5, lvs, Etc.) lets multiple channels share a group of Servers. When we branch the site program to more than one server, because the session is limited by the implementation of the principle, can not be synchronized across the server update session, so that the login state is difficult to share through the Session.

We use the Memcache+cookie scheme to solve the problem of distributed system sharing login Status.

Memcache server itself is a socket service side, internal data in the form of key-value pairs stored in the Server's memory, essentially a large hash table. The deletion of data takes the lazy removal mechanism. Although Memcache does not provide clustering functionality, it is easy to implement a memcache cluster configuration through a client-side driver.

Let's briefly introduce the use of Memcache

1. Download and install Memcache (windows Platform)

(1) Unzip the program to any location on the disk

(2) go to cmd window, run memcached.exe-d install installation service, Open the service window after installation to see if the service is installed Successfully.

(3) start the service directly in service management, or use the cmd command net start "Memcache Server"

(4) use Telnet to connect to the Memcache console to verify that the service is normal telnet 127.0.0.1 11211

View current Memcache Server status using the stats directive

2. Usage in the program

(1) adding Memcached.ClientLibrary.dll references in the program

(2) code example for manipulating Memcache in C #

string[] serverlist = {"192.168.1.100:11211","192.168.1.101:11211"  };//Initialize the pool for memcache serversSockiopool pool = sockiopool.getinstance ("Test");p Ool. Setservers (serverlist);p Ool. Initialize (); MC=Newmemcacheclient (); Mc. Poolname="Test"; mc. EnableCompression=false;p Ool. Shutdown ();//Close Connection Pool

Below we do the concrete implementation of the plan

1. First introduce the Memcached.ClientLibrary.dll in the common layer and encapsulate the Memcache helper class, memcachehelper

usingmemcached.clientlibrary;usingSystem;namespacepms.common{ public classMemcachehelper {Private Static ReadOnlyMemcachedclient Mc =NULL; Staticmemcachehelper () {//best placed in configuration file           string[] serverlist = {"127.0.0.1:11211","10.0.0.132:11211" }; //Initialize Pool           varPool =sockiopool.getinstance (); Pool.           Setservers (serverlist); Pool. Initconnections=3; Pool. Minconnections=3; Pool. MaxConnections=5; Pool. Socketconnecttimeout= +; Pool. Sockettimeout= the; Pool. Maintenancesleep= -; Pool. Failover=true; Pool. Nagle=false; Pool.           Initialize (); //get the client instanceMc =NewMemcachedclient {enablecompression =false}; }       /// <summary>       ///Storing Data/// </summary>       /// <param name= "key" ></param>       /// <param name= "value" ></param>       /// <returns></returns>        public Static BOOLSet (stringKeyObjectValue) {          returnMc.set (key, value); }        public Static BOOLSet (stringKeyObjectValue,datetime Time) {           returnMc.set (key, value,time); }       /// <summary>       ///Get Data/// </summary>       /// <param name= "key" ></param>       /// <returns></returns>        public Static ObjectGet (stringKey) {           returnMc.get (key); }       /// <summary>       ///Delete/// </summary>       /// <param name= "key" ></param>       /// <returns></returns>        public Static BOOLDelete (stringKey) {           returnMc.keyexists (key) &&Mc.delete (key); }    }}

2. Change the user login method userlogin, the user log on successfully generated a guid, the GUID is stored in a cookie and a GUID key to the logon user information serialized into the Memcache server.

 publicActionResult userlogin () {#regionVerification Code CheckvarValidatecode = session["Validatecode"] !=NULL? session["Validatecode"]. ToString ():string.    Empty; if(string. IsNullOrEmpty (validatecode))returnContent ("no: Verification Code Error !"); session["Validatecode"] =NULL; varTxtcode = request["Validatecode"]; if(!validatecode.equals (txtcode, Stringcomparison.invariantcultureignorecase))returnContent ("no: Verification Code Error !"); #endregion    varUserName = request["UserName"]; varUserpwd = request["PassWord"]; //querying whether a user exists    varuser = Userservice.loadentities (u = U.username = = UserName && U.password = =userpwd).    FirstOrDefault (); if(user = =NULL)returnContent ("no: Login Failed"); //generates a GUID value as the key for the Memache.    varSessionId =Guid.NewGuid ().    ToString (); //stores the logged-in user information in the Memcache. Memcachehelper.set (sessionId, serializehelper.serializetostring (user), DateTime.Now.AddMinutes ( -)); //The Memcache key is returned to the browser as a Cookie. response.cookies["sessionId"]. Value =sessionId; returnContent ("ok: Login Successful");}

3. Change the OnActionExecuting method of the login check controller filtercontroller to change the check mode to read from the Memcache server the object with the value of the key in the Cookie:

protected Override voidonactionexecuting (actionexecutingcontext Filtercontext) {Base.    OnActionExecuting (filtercontext); //if (session["user"] = = Null)    if(request.cookies["sessionId"] !=NULL)    {        varSessionId = request.cookies["sessionId"].        Value; //based on this value, check memcache.        varobj =Memcachehelper.get (sessionId); if(obj = =NULL) {filtercontext.result= Redirect ("/login/index"); return; }        varuser = Serializehelper.deserializetoobject<user>(obj.        ToString ()); Loginuser=user; //simulates the sliding expiration Time.Memcachehelper.set (sessionId, obj, DateTime.Now.AddMinutes ( -)); }    ElseFiltercontext.result= Redirect ("/login/index");}

[MVC study notes] 6. Use Memcache+cookie to resolve distributed system shared login status

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.