C # Development Load Balancing Server instance

Source: Internet
Author: User
Tags allkeys current time exception handling httpcontext servervariables nginx server nginx load balancing

train of Thought

Load balancing server most famous when the number of nginx. The Nginx server transmits the connection to the intranet and N servers by asynchronous way, which is used to decompose the pressure of the single application server, understand the principle and the scene, and realize one with C #. Ideas are as follows:

1. Use the application_beginrequest of a site to receive connections and forward connections.

2. Separate handling of all types of static resources (may not be transferred)

3. Can forward Get,post, asynchronous forwarding.

4. Forward to the same server for the specified request, maintaining the user's login status.

Implement

Vs2015 built an MVC construction station: Localhost:1500/. Modify the web.config to receive all connections.

<system.webServer>
<modules runallmanagedmodulesforallrequests= "true" >
</modules>
</system.webServer>

Introducing MyCmn.dll (HTTP://CODE.TAOBAO.ORG/SVN/MYOQL/LIBS4), myhelper encapsulates the type conversion function for ease of use.

The code is as follows:

public class Requestwrap
{
Public HttpWebRequest Request {get; set;}
Private ManualResetEvent Event {get; set;}
Private actionPublic Requestwrap (HttpWebRequest request)
{
Event = new ManualResetEvent (false);
This. request = Request;
}

public void Run (Action{
This. Action = Act;

Request.begingetresponse (New AsyncCallback (Getresponsecallback), this);
This. Event.waitone (15000);
}

private static void Getresponsecallback (IAsyncResult asyncresult)
{
Requestwrap wrap = (requestwrap) asyncresult.asyncstate;
HttpWebResponse response = null;
Try
{
Response = Wrap. Request.endgetresponse (asyncresult) as HttpWebResponse;
}
catch (WebException ex)
{
Response = ex. Response as HttpWebResponse;
}
Wrap. Action (response);
Wrap. Event.set ();
}
}

private void Application_BeginRequest (Object source, EventArgs E)
{
var lastextname = "";
{
var lastindex = Request.Url.LocalPath.LastIndexOf ('. ');
if (lastindex > 0)
{
Lastextname = Request.Url.LocalPath.Slice (lastindex);
}
}

<modules runallmanagedmodulesforallrequests= "True" > settings, static resources are coming in.
if (Lastextname.isin (". js", ". css", ". html", ". htm", ". png", ". jpg", ". gif"))
{
Return
}

HttpWebRequest myrequest = (HttpWebRequest) webrequest.create (gettransferhost () + Request.rawurl);
Myrequest.proxy = null;

Myrequest.timeout = 15000;
Myrequest.readwritetimeout = 3000;

Myrequest.method = Request.httpmethod;

Request.Headers.AllKeys.All (k =>
{
if (! Webheadercollection.isrestricted (k))
{
MyRequest.Headers.Add (k, request.headers[k]);
}
Else
{
var val = request.headers[k];
if (k.is ("Range"))
{
Myrequest.addrange (Val. Asint ());
}
else if (k.is ("If-modified-since"))
{
Myrequest.ifmodifiedsince = val. Asdatetime ();
}
else if (k.is ("Accept"))
{
Myrequest.accept = val;
}
else if (k.is ("Content-type"))
{
Myrequest.contenttype = val;
}
else if (k.is ("Expect"))
{
Myrequest.expect = val;
}
else if (k.is ("Date"))
{
Myrequest.date = val. Asdatetime ();
}
else if (k.is ("Host")
{
Myrequest.host = val;
}
else if (k.is ("Referer"))
{
Myrequest.referer = val;
}
else if (k.is ("transfer-encoding"))
{
Myrequest.transferencoding = val;
}
else if (k.is ("User-agent"))
{
Myrequest.useragent = val;
}
else if (k.is ("Connection"))
//{
O.connection = val;
//}
else if (k.is ("KeepAlive"))
{
Myrequest.keepalive = val. Asbool ();
}
}
return true;
});

using (var readstream = request.inputstream)
{
while (true)
{
byte[] Readbuffer = new byte[1024];
var readlength = readstream.read (readbuffer, 0, readbuffer.length);
if (Readlength = = 0) break;
Myrequest.getrequeststream (). Write (readbuffer, 0, readlength);
}
}

New Requestwrap (Myrequest). Run (Myresponse =>
{
MyResponse.Headers.AllKeys.All (k =>
{
if (k.is ("x-powered-by"))
{
return true;
}
RESPONSE.HEADERS[K] = myresponse.headers[k];
return true;
});

using (var Readstream = Myresponse.getresponsestream ())
{

while (true)
{
byte[] Readbuffer = new byte[1024];
var read = Readstream.read (readbuffer, 0, readbuffer.length);
if (read = = 0) break;
Response.OutputStream.Write (readbuffer, 0, read);
}
}
Response.statuscode = MyResponse.StatusCode.AsInt ();
});
Response.End ();
}

public static string Getclientipaddress ()
{
if (httpcontext.current = null)
return string. Empty;
HttpContext context = Httpcontext.current;//system.web.httpcontext.current;

string ipaddress = context. request.servervariables["Http_x_forwarded_for"];

if (!string. IsNullOrEmpty (IPAddress))
{
String[] addresses = Ipaddress.split (', ');
if (addresses. Length!= 0)
{
return addresses[0];
}
}

return context. request.servervariables["REMOTE_ADDR"]; + "host" + context. request.userhostaddress;
}


private String Gettransferhost ()
{
String[] hosts = new string[] {"http://localhost"};

var index = getclientipaddress (). Last ()% hosts. Length;

return Hosts[index];
}

explain

Where Requestwrap is the request class that wraps the asynchronous request. Encapsulates a Run method for asynchronous invocation. Filter the application server's postback header x-powered-by

About Webheadercollection.isrestricted is due to an error: Exception handling: You must modify this header with the appropriate property or method, article address: http://blog.useasp.net/archive/2013/ 09/03/the-methods-to-dispose-http-header-cannot-add-to-webrequest-headers.aspx, excerpts are as follows:
You can set the header for other restrictions here.
Attention:
Range HTTP headers are added by AddRange
If-modified-since HTTP headers are set through the Ifmodifiedsince property
Accept is set by the Accept property.
The Connection is set by the Connection property and the KeepAlive property.
Content-length is set by the ContentLength property.
Content-type is set by the ContentType property.
Expect is set by the Expect property.
Date is set by the Date property and defaults to the current time of the system.
Host is set by the system as the current host information.
Referer is set by the Referer property.
Transfer-encoding is set by the TransferEncoding property (the SendChunked property must be true).
User-agent is set by the UserAgent property.


asp.net how does C # do distributed load Balancing? Specific ideas?

Last year for a customer based on nginx load balancing, and then add some new practice, summed up, willing to share. In fact, the project I am currently in touch with is not large, and it has not been done on very large projects (such as transactional and logical-intensive, massively concurrent applications), and if someone has a better plan in the relevant field, welcome to explore. Distributed programs are very different from running a single instance, so make sure your application is better prepared in the development phase before you distribute it. A completely for a single server environment development applications, in order to be in a distributed balanced system to run perfectly, the number of work to be done will make operators crazy. IIS provides the ability to deploy Web Farm to a specific Web site on the same server, with multiple processes for its application pool. This method can be programmed to simulate the application in the distributed environment of the operation, such as session, Cache sharing and identity verification. However, because distributed load balancing typically uses a reverse proxy to perform the transmission between the portal server and multiple distributed computing servers, in a distributed load-balancing environment, running on different servers (or different instances of IIS sites on the same server) may be in Request URL operations, file storage, These aspects, such as relative path mapping, differ from single instance runtime. Therefore, in the preparation phase please make sure that you have solved these problems, here I will not expand, after all, for different applications will have different specific work. Then, the next job seems very easy. The general idea of distributed load balancing is that the whole system has only one unified entrance, and then the unified entry E will request "reverse" proxy to multiple operation server S by the configured equalization rule, and finally output the result from the S operation to the client. On each s, the same configuration is used for single instance: Each S is a normal server in a common deployment mode: Therefore, it is necessary to connect their database connection string, session provider, Cache provider, form authentication required MachineKey and other related resources to the unified location or for unified processing, to ensure that all S working state consistency (that is, when the user's request to any S, the session state, the cache state, etc.). On the reverse proxy software of E, all S are configured and perfected according to the policy (including server location, port and weight, proxy IP and original host first). For security reasons, you can restrict access for all S to only e access, and E should be configured to be publicly accessible, and finally resolve the domain name to E. Note that all subsequent requests are first reached on E and then assigned by E to a specific S according to the configured policy. Therefore, if the application has upload files, custom MIME types, error pages, etc. can beFeatures that can be associated with IIS default restrictions/functions, and note the consistency of E and S on these configurations. In addition, for the reverse agent software to be used on E, you can use the widely known nginx, or you can use Microsoft's integrated Application Request Routing component (ARR) with IIS.

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.