MVC uses Memcache+cookie to solve distributed system shared login Status Learning notes 6_ practical skills

Source: Internet
Author: User
Tags datetime memcached

In order to solve the bottleneck of stand-alone processing, to enhance the availability of software, we need to deploy the software on multiple servers to enable multiple two-level subdomains to be channel-enabled, to deploy the site to a separate server based on business functions, or through load-balancing techniques such as DNS polling, Radware, F5, LVS, etc.) lets multiple channels share a set of servers. When we put the site program division to more than one server, because session by the implementation of the principle of limitations, can not sync update session across the server, making the login state difficult to share through the session.

We use the Memcache+cookie solution to solve the problem of shared login status in distributed systems.

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

Let's briefly introduce the usage of memcache.

1. Download and install Memcache (Windows platform)

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

(2) Enter the cmd window, run memcached.exe-d Install installation service, open the service window after installation to see if the service was installed successfully.

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

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

Use the Stats directive to view current Memcache server status

2. Usage in the program

(1) Add a Memcached.ClientLibrary.dll reference to 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 servers
Sockiopool pool = sockiopool.getinstance ("test");
Pool. Setservers (serverlist);
Pool. Initialize ();
MC = new Memcacheclient ();
Mc. poolname = "Test";
Mc. EnableCompression = false;
Pool. 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 help class, Memcachehelper

Using Memcached.clientlibrary;

Using System;

 Namespace Pms.common {public class Memcachehelper {private static readonly memcachedclient Mc = null;

 Static Memcachehelper () {//best placed in configuration file string[] serverlist = {"127.0.0.1:11211", "10.0.0.132:11211"};
 Initialize pool = Sockiopool.getinstance (); Pool.

 Setservers (serverlist); Pool.
 Initconnections = 3; Pool.
 Minconnections = 3; Pool.

 MaxConnections = 5; Pool.
 socketconnecttimeout = 1000; Pool.

 Sockettimeout = 3000; Pool.
 Maintenancesleep = 30; Pool.

 Failover = true; Pool.
 Nagle = false; Pool.

 Initialize ();
 Get Client Instance Mc = new Memcachedclient {enablecompression = false}; ///<summary>///Storage data///</summary>///<param name= "key" ></param>///<param name= "va Lue "></param>///<returns></returns> public static Boolean Set (string Key,object value) {return Mc .
 Set (key, value); public static Boolean Set (String key, Object Value,datetime time) {return Mc.set (key, VAlue,time); ///<summary>///Get data///</summary>///<param name= "key" ></param>///<returns>&lt
 ;/returns> public static object get (String key) {return mc.get (key); }///<summary>///delete///</summary>///<param name= "key" ></param>///<returns></
 returns> public static bool Delete (string key) {return mc.keyexists (key) && mc.delete (key);

 }
 }
}

2. Change the user login method Userlogin, the user login successfully generates a GUID, the GUID is stored in a cookie and the login user information is serialized into the Memcache server with the GUID key.

Public ActionResult Userlogin () {#region Authenticode checksum var validatecode = session["Validatecode"]!= null? session["Validatecode"]. ToString (): String.
 Empty; if (string.
 IsNullOrEmpty (Validatecode)) return Content ("No: Validation code error!!");
 session["Validatecode"] = null;
 var txtcode = request["Validatecode"];
 if (!validatecode.equals (Txtcode, stringcomparison.invariantcultureignorecase)) return Content ("No: Validation code error!!");
 #endregion var userName = request["UserName"];
 var userpwd = request["PassWord"]; Query whether the user exists var user = userservice.loadentities (u => u.username = = UserName && U.password = userpwd).
 FirstOrDefault ();

 if (user = null) return Content ("No: Login Failed");
 Produces a GUID value as the Memache key. var sessionId = Guid.NewGuid ().
 ToString ();
 Store the logged in user information in Memcache.
 Memcachehelper.set (SessionId, serializehelper.serializetostring (user), DateTime.Now.AddMinutes (20));
 Returns the Memcache key as a cookie to the browser. response.cookies["SessionId"].
 Value = sessionId;
Return Content ("OK: Login successful");

 }

3. Change the login verification controller Filtercontroller OnActionExecuting method, so that its check mode to read from the Memcache server in the cookie value of the Key object:

protected override void OnActionExecuting (ActionExecutingContext filtercontext)
{
 base. OnActionExecuting (filtercontext);
 if (session["user" = = null)
 if (request.cookies["sessionId"]!= null)
 {
 var sessionId = request.cookies[ "SessionId"]. Value;
 Check Memcache according to this value.
 var obj = memcachehelper.get (sessionId);
 if (obj = = null)
 {
 Filtercontext.result = Redirect ("/login/index");
 return;
 }
 var user = serializehelper.deserializetoobject<user> (obj. ToString ());
 Loginuser = user;
 Simulate the sliding expiration time.
 Memcachehelper.set (sessionId, obj, DateTime.Now.AddMinutes); 
 }
 else
 Filtercontext.result = Redirect ("/login/index");
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.