很多情況下基於wcf的複雜均衡都首選zookeeper,這樣可以擁有更好的控制粒度,但zk對C# 不大友好,實現起來相對來說比較麻煩,實際情況下,如果
你的負載機制粒度很粗糙的話,優先使用nginx就可以搞定,既可以實現複雜均衡,又可以實現雙機熱備,以最小的程式碼量實現我們的業務,下面具體分享下。
一:準備的材料
1. 話不多說,一圖勝千言,圖中的伺服器都是採用vmware虛擬化,如下圖:
《1》 三臺windows機器 ,兩個WCF的windows伺服器承載(192.168.23.187,192.168.23.188),一臺Client的伺服器(192.168.23.1)
《2》 一臺Centos機器,用來承載web複雜均衡nginx(192.168.23.190)。
《3》在所有的Client的Hosts檔案中增加host對映:【192.168.23.190 cluster.com】,方便通過域名的形式訪問nginx所在伺服器的ip地址。
二:環境搭建
1. WCF程式
既然是測試,肯定就是簡單的程式,程式碼就不完全給出了。
《1》 HomeService實現類程式碼如下(輸出當前server的ip地址,方便檢視):
1 public class HomeService : IHomeService 2 { 3 public string DoWork(string msg) 4 { 5 var ip = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(i => i.AddressFamily == 6 AddressFamily.InterNetwork).ToString(); 7 8 return string.Format("當前 request 由 server={0} 返回", ip); 9 } 10 }
《2》 App.Config程式碼
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <startup> 4 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> 5 </startup> 6 <system.serviceModel> 7 <behaviors> 8 <serviceBehaviors> 9 <behavior name=""> 10 <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> 11 <serviceDebug includeExceptionDetailInFaults="false" /> 12 </behavior> 13 </serviceBehaviors> 14 </behaviors> 15 <services> 16 <service name="WcfService.HomeService"> 17 <endpoint address="/HomeService" binding="basicHttpBinding" contract="WcfService.IHomeService"> 18 <identity> 19 <dns value="localhost" /> 20 </identity> 21 </endpoint> 22 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 23 <host> 24 <baseAddresses> 25 <add baseAddress="http://192.168.23.187:8733" /> 26 </baseAddresses> 27 </host> 28 </service> 29 </services> 30 </system.serviceModel> 31 </configuration>
因為windows的兩臺機器的ip地址是192.168.23.187,192.168.23.188,所以部署的時候注意一下config中的baseAddress地址。
2. centos上的nginx搭建
nginx我想大家用的還是比較多的,去官網下載最新的就好【nginx-1.13.6】:http://nginx.org/en/download.html,下載之後,就是常規的三板斧安裝!!!
[root@localhost nginx-1.13.6]# yum install -y gcc gcc-c++ automake pcre pcre-devel zlib zlib-devel openssl openssl-devel
[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 koi-utf nginx.conf uwsgi_params fastcgi.conf.default koi-win nginx.conf.default uwsgi_params.default fastcgi_params mime.types scgi_params win-utf fastcgi_params.default mime.types.default scgi_params.default [root@localhost conf]# vim nginx.conf
詳細配置如下,注意下面“標紅”的地方,權重按照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 '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #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's document root # concurs with nginx'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. client端的程式搭建
《1》 第一件事就是將 192.168.23.190 對映到本機的host中去,因為服務不提供給第三方使用,所以加host還是很輕鬆的。
192.168.23.190 cluster.com
《2》 然後就是client端程式新增服務引用,因為新增了host對映,所以服務引用地址就是"http://cluster.com"。 程式碼如下:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 for (int i = 0; i < 1000; i++) 6 { 7 HomeServiceClient client = new HomeServiceClient(); 8 9 var info = client.DoWork("hello world!"); 10 11 Console.WriteLine(info); 12 13 System.Threading.Thread.Sleep(1000); 14 } 15 16 Console.Read(); 17 } 18 }
最後來執行以下程式,看看1000次迴圈中,是不是按照權重1:5 的方式對後端的wcf進行呼叫的???
看到沒有,是不是很牛逼,我只需要通過cluster.com進行服務訪問,nginx會自動給我複雜均衡,這就是我們開發中非常簡單化的wcf複雜均衡。
希望本篇對你有幫助~~~~ 附完整原始碼:cluster.zip