Simplified WCF Load Balancing Solution

Source: Internet
Author: User

Recently, I spoke with instructor Gao about the load balancing solution for nginx and tomcat clusters. Interesting. I thought about the WCF technology used in my project, so I thought about how to implement load balancing in WCF. After a while, Google found that the routing service of wcf4.0 seemed to be able to be implemented. However, during the study of the routing service, I had a solution, haha.

I want to deploy a WCF balancing server between the client and the WCF Service to distribute requests and simulate nginx work.

I also use WCF to implement the WCF balanced server. All service interfaces are exposed to the client through the balanced service area. For the client, as long as the service is called normally, add the remote service reference of the balancer.

Implementation: 1. Balance the service library
Namespace wcfsimplebalance {// <summary> // Load Balancing base class /// </Summary> /// <typeparam name = "T"> </typeparam> public class wcfbalance <t> {private channelfactory <t> _ channelfactory; public t balanceproxy {Get; set;} public wcfbalance (string servicename) {string endpoint = endpointbalance. getbalanceendpoint (servicename); // obtain the random endpoint this. _ channelfactory = new channelfactory <t> (endpoint); this. balanceproxy = This. _ channelfactory. createchannel ();}}}

Generic T is a protocol in which the WCF channel can be dynamically built.

Namespace wcfsimplebalance {internal class endpointbalance {// <summary> // balance node configuration /// </Summary> Private Static list <wcfbalancesection> _ wcfbalancecfg; static endpointbalance () {_ wcfbalancecfg = configurationmanager. getsection ("wcfbalance") as list <wcfbalancesection> ;} /// <summary> /// random endpoint /// </Summary> /// <Param name = "servicename"> </param> /// <returns> </returns> Public static string getbalanceendpoint (string servicename) {var servicecfg = _ wcfbalancecfg. single (S => S. servicename = servicename); var ran = new random (); int I = ran. next (0, servicecfg. endpoints. count); string endpoint = servicecfg. endpoints [I]; console. writeline (endpoint); Return endpoint ;}}}
This class provides a static method to randomly configure an endpoint from the configuration file based on the service name. Random Number algorithms may not be evenly distributed. I don't know how to do this.
namespace WcfSimpleBalance{
/// <Summary> /// configure the model /// </Summary> internal class wcfbalancesection {Public String servicename {Get; set;} public list <string> endpoints {Get; set ;}}
/// <Summary> /// custom configuration processing /// </Summary> public class wcfbalancesectionhandler: iconfigurationsectionhandler {public object create (Object parent, object configcontext, xmlnode Section) {var Config = new list <wcfbalancesection> (); foreach (xmlnode node in section. childnodes) {If (node. name! = "Balanceservice") throw new configurationerrorsexception ("Unrecognized configuration items", node); var item = new wcfbalancesection (); foreach (xmlattribute ATTR in node. attributes) {Switch (ATTR. name) {Case "servicename": item. servicename = ATTR. value; break; Case "endpoints": item. endpoints = ATTR. value. split (','). tolist (); break; default: Throw new configurationerrorsexception ("Unrecognized configuration attributes", ATTR) ;}} config. add (item) ;}return config ;}}}
These two are used to process the configuration file.
2. Common WCF Service Agreements:
namespace WcfServiceContracts{     [ServiceContract(Name = "CalculatorService")]    public interface IAdd    {         [OperationContract]         int Add(int x, int y);    }}

 

A simple addition.

WCF Service implementation:
namespace WcfService{    public class AddServices:IAdd    {        public int Add(int x, int y)        {            return x + y;        }    }}

 

3. Implementation of the WCF balancer

Create a new WCF Service class library, reference the same protocol, and reference the above balanced class library

namespace WcfServiceBalance{    public class AddServices : WcfBalance<IAdd>, IAdd    {        public AddServices()            : base("AddServices")        {        }        public int Add(int x, int y)        {            return BalanceProxy.Add(x, y);        }    }}

 

Inherits the wcfbalance and protocol interfaces. The constructor calls the constructor of the base class and passes in the service name. Add to directly call the method of the base class.

Simulation: 1. WCF server boarding

The WCF Service can be hosted under multiple schemes, such as IIS, win service, and console. The host is directly hosted on the console for convenience.

Create two console programs and host a common WCF Service. A boarding WCF balance service. The code is not shown in the table and the service address is provided.

Three Common Services. (Copy three copies of the bin directory of the console program of the boarding common service, and change the three ports to three services)

Http: // localhost: 8081/WCF

Http: // localhost: 8082/WCF

Http: // localhost: 8083/WCF

Balance Service

HTTP: /localhost: 8088/wcfbalance

Configuration File

Define the endpoints of all backend servers in the configuration file of the balancing server, and then configure them in the Custom wcfbalance node. The endpoint list corresponding to the service name is separated by commas.

<?xml version="1.0" encoding="utf-8" ?><configuration>  <configSections>    <section name="wcfBalance" type="WcfSimpleBalance.WcfBalanceSectionHandler, WcfSimpleBalance" />  </configSections>    <wcfBalance>       <balanceService ServiceName="AddServices"  Endpoints="AddService1,AddService2,AddService3" />    </wcfBalance>  <system.serviceModel>    <bindings>      <basicHttpBinding>        <binding name="BasicHttpBinding_CalculatorService" />      </basicHttpBinding>    </bindings>    <client>      <endpoint address="http://localhost:8081/Wcf" binding="basicHttpBinding"          bindingConfiguration="BasicHttpBinding_CalculatorService"          contract="WcfServiceContracts.IAdd" name="AddService1" />      <endpoint address="http://localhost:8082/Wcf" binding="basicHttpBinding"          bindingConfiguration="BasicHttpBinding_CalculatorService"          contract="WcfServiceContracts.IAdd" name="AddService2" />      <endpoint address="http://localhost:8083/Wcf" binding="basicHttpBinding"          bindingConfiguration="BasicHttpBinding_CalculatorService"          contract="WcfServiceContracts.IAdd" name="AddService3" />    </client>  </system.serviceModel>    <startup>         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />    </startup></configuration>
2. Client call

Add a balance server reference and call it in code.

Start 30 threads to run the service.

namespace WcfServiceClient{    class Program    {        static void Main(string[] args)        {            for (int i = 0; i < 30; i++)            {                var thread = new Thread(new ThreadStart(CallAdd));                thread.Start();            }            Console.Read();        }        private static void CallAdd()        {            using (var proxy = new CalculatorServiceClient())            {                proxy.Add(1,2);            }        }    }}
Running result:

Requests are distributed to three services, but they seem uneven. This is related to algorithms.

Through the above implementation, we have implemented a simple WCF balanced server. This is just a simple solution, and there are certainly many issues that have not been taken into account. I hope you will discuss them.

However, I think that although requests are distributed, balancing servers will become another bottleneck in the face of a real high-concurrency environment.

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.