>  기사  >  운영 및 유지보수  >  nginx를 사용하여 고가용성, 동시성 wcf 클러스터 구축

nginx를 사용하여 고가용성, 동시성 wcf 클러스터 구축

PHP中文网
PHP中文网원래의
2017-10-23 10:48:042856검색

주키퍼는 더 나은 제어 세분성을 가질 수 있는 wcf 기반의 복잡한 밸런싱을 위한 첫 번째 선택입니다. 그러나 zk는 C#에 친숙하지 않으며

세분성이 있는 경우 실제 상황에서 구현하기가 상대적으로 까다롭습니다. 로드 메커니즘이 매우 어려우면 먼저 nginx를 사용하여 완료할 수 있습니다. 복잡한 균형과 이중 머신 핫 백업을 달성할 수 있으며, 최소한의 코드로 비즈니스를 구현할 수 있습니다. 아래에서 자세히 설명하겠습니다. .

1: 준비된 자료

1. 말할 것도 없고, 천 마디 말보다 한 장의 사진이 더 중요합니다. 사진 속 서버는 아래와 같이 모두 vmware로 가상화되어 있습니다.

《1》 Windows 머신 3개, WCF 창 2개 서버 호스트(192.168.23.187, 192.168.23.188), 클라이언트 서버(192.168.23.1)

《2》 웹 컴플렉스 균형 nginx(192.168.23.190)를 호스팅하는 데 사용되는 Centos 머신입니다.

《3》모든 클라이언트 호스트 파일에 호스트 매핑을 추가합니다: [192.168.23.190 Cluster.com] 도메인 이름을 통해 nginx가 위치한 서버의 IP 주소에 대한 액세스를 용이하게 합니다.

둘: 환경 설정

1. WCF 프로그램

테스트이므로 간단한 프로그램이어야 하며 코드가 완전히 제공되지는 않습니다.

《1》 HomeService 구현 클래스 코드는 다음과 같습니다. (보기 쉽게 현재 서버의 IP 주소를 출력합니다.)

 public class HomeService : IHomeService 
     { 
         public string DoWork(string msg) 
         { 
             var ip = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(i => i.AddressFamily == 
                                                         AddressFamily.InterNetwork).ToString(); 
 
             return string.Format("当前 request 由 server={0} 返回", ip); 
         }
       
     }


《2》App.Config code

 <?xml version="1.0" encoding="utf-8" ?> 
 <configuration> 
   <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> 
  </startup> 
   <system.serviceModel> 
     <behaviors> 
       <serviceBehaviors> 
         <behavior name="">

           <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />

           <serviceDebug includeExceptionDetailInFaults="false" />
         </behavior>

       </serviceBehaviors>

     </behaviors>

     <services>

       <service name="WcfService.HomeService">

         <endpoint address="/HomeService" binding="basicHttpBinding" contract="WcfService.IHomeService">

           <identity>

             <dns value="localhost" />

           </identity>

         </endpoint>

         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

         <host>

           <baseAddresses>

             <add baseAddress="http://192.168.23.187:8733" />

           </baseAddresses>

         </host>

       </service>

     </services>

   </system.serviceModel>

 </configuration>


windows 때문에 두 머신의 IP 주소는 192.168.23.187과 192.168.23.188이므로 배포 시 구성의 baseAddress 주소에 주의하세요.

2. centos에서 nginx 설정하기

다들 nginx를 더 많이 사용하는 것 같은데, 공식 웹사이트에 가서 최신 버전을 다운로드하세요. [nginx-1.13.6]: http://nginx.org/en/download .html을 다운로드 후 일반 Sanbanaxe 설치입니다! ! !

[root@localhost nginx-1.13.6]# ./configure --prefix=/usr/myapp/nginx
[root@localhost nginx-1.13.6]# make && make install

그런 다음 nginx에서 설치 디렉터리에서 conf 파일을 찾아 내부에서 nginx.conf 구성을 수정합니다.

[root@localhost nginx]# cd conf
[root@localhost conf]# ls
fastcgi.conf                                                                                               nginx.conf.default uwsgi_params.defaultfastcgi_params mime 유형               scgi_params                                         ' ' s ' s의 s                               ‐ ‐ ‐ ‐ ‐ ‐ ‐                                                                                                                                                           빨간색으로 표시된 부분은 무게를 1:5 방식으로 전화하시면 됩니다.

#user  nobody; worker_processes 
 1; #error_log  logs/error.log;
  #error_log  logs/error.log  notice; 
  #error_log  logs/error.log  info; 
  #pid logs/nginx.pid; events {  
    worker_connections  1024; } 
    http {   
     include       mime.types;   
      default_type  application/octet-stream;  
        #log_format  main  &#39;$remote_addr - $remote_user [$time_local] "$request" &#39;    #                 
         &#39;$status $body_bytes_sent "$http_referer" &#39;    #                  &#39;
         "$http_user_agent" "$http_x_forwarded_for"&#39;;   
          #access_log  logs/access.log  
          main;    sendfile        
          on;    #tcp_nopush     
          on;    #keepalive_timeout  0;    keepalive_timeout  65;    #gzip  
          on;    
   upstream  cluster.com{        
    server 192.168.23.187:8733 weight=1;        
     server 192.168.23.188:8733 weight=5;           
  }    
  server {        
  listen       80;       
   server_name  localhost;        
   #charset koi8-r;       
    #access_log  logs/host.access.log  main;       
       location / {            
       root   html;            index  index.html index.htm;            
       proxy_pass http://cluster.com;            #设置主机头和客户端真实地址,以便服务器获取客户端真实IP           
         proxy_set_header X-Forwarded-Host $host;        
             proxy_set_header X-Forwarded-Server $host;           
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;           
               proxy_set_header  X-Real-IP  $remote_addr;        }       
                #error_page  404              /404.html;       
                 # redirect server error pages to the static page /50x.html     
                    #        error_page   500 502 503 504  /50x.html;
                            location = /50x.html {          
                              root   html;        }       
                  # proxy the PHP scripts to Apache listening on 127.0.0.1:80    
                  #        #location ~ \.php$ {   
					#    proxy_pass   http://127.0.0.1;    
				#}       
				# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000       
				#        #location ~ \.php$ {        #    root           html;  
				#    fastcgi_pass   127.0.0.1:9000;        #    fastcgi_index  index.php;
				#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name; 
				#    include        fastcgi_params;       
				#}        # deny access to .htaccess files,
				if Apache&#39;s document root        # concurs
				with nginx&#39;s one       

 #        #location ~ /\.ht {    

#    deny  all;        #} 
 }    # another virtual host using mix of IP-, name-, and port-based configuration   
  #    #server {   
   #    listen       8000;   
    #    listen       somename:8080;    
    #    server_name  somename  alias  another.alias;    
    #    location / {    #        root   html;   
     #        index  index.html index.htm;    #    }    
     #}    # HTTPS server    #    #server {   
	       #    listen       443 ssl;   
	        #    server_name  localhost;   
	         #    ssl_certificate      cert.pem;   
	          #    ssl_certificate_key  cert.key;    
	          #    ssl_session_cache    shared:SSL:1m;   
	           #    ssl_session_timeout  5m;    
	           #    ssl_ciphers  HIGH:!aNULL:!MD5;   
	            #    ssl_prefer_server_ciphers  on;    
	            #    location / {    #        root   html;   
	             #        index  index.html index.htm;   
             #    }    #} }



3. 클라이언트 측 프로그램 구축

《1》 먼저 192.168.23.190을 로컬 호스트에 매핑해야 합니다. 서비스가 제3자에게 제공되지 않기 때문에 호스트를 추가하는 것이 좋습니다. 매우 편안합니다.

192.168.23.190 Cluster.com


《2》 그런 다음 클라이언트 프로그램은 서비스 참조를 추가하며 코드는 다음과 같습니다.


  class Program

    { 
         static void Main(string[] args) 
        { 
             for (int i = 0; i < 1000; i++) 
            { 
                 HomeServiceClient client = new HomeServiceClient(); 

                 var info = client.DoWork("hello world!");


               Console.WriteLine(info);
               

                System.Threading.Thread.Sleep(1000);14            }
           


           Console.Read();
           
        }
       
  }


마지막으로 다음 프로그램을 실행하고 확인합니다. 1000 루프, 백엔드 wcf는 1:5의 가중치에 따라 호출됩니까? ? ?


정말 멋지지 않나요? Cluster.com을 통해서만 서비스에 액세스하면 nginx가 자동으로 복잡한 밸런싱을 제공합니다. 이는 개발 균형에서 매우 단순화된 wcf 복잡성입니다. .


위 내용은 nginx를 사용하여 고가용성, 동시성 wcf 클러스터 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.