nginx分散式例項入門操作
本文目的
前段時間學習WCF已經漸入佳境,完成了既定學習目標,轉入分散式系統學習。本文技術路線是:
採用wcf實現分散式服務端和客戶端,客戶端部署於本地主機,nginx和WCF部署於虛擬機器端(分別是三個虛擬機器)
此文驗證:當其中一個服務端斷線後,另一個服務端可以繼續支撐整個會話的完成。
技術關鍵詞
wcf,nginx,虛擬機器
(如果wcf基礎知識還不是很熟,建議先學習wcf技術知識。虛擬機器採用vmware,虛擬機器建立的系統是Win7.
提前準備好虛擬機器,並建立三個虛擬機器,每個虛擬機器建立Win7系統,每個Win7系統安裝.NET4.6平臺。
下載nginx程式包。)
準備工作:虛擬機器與主機建立區域網
為了保障本文的測試成功,主機與三個虛擬機器之間組成區域網。三個虛擬機器完成下圖設定
三個虛擬機器完成虛擬網路設定:
選擇VMnet8(因為此項外部連線是NAT模式),然後點選NAT設定。
設定NAT閘道器設定
三個虛擬機器還需要關閉防火牆和修改入站規則
我們來從自己本地主機ping虛擬機器進行驗證。
我們從虛擬機器向本地主機ping
以上就實現了每個虛擬機器與主機的區域網建立。
wcf契約與Service
本文的wcf服務程式碼沒有很特殊的地方,貼程式碼
1 namespace NginxWCFTest_Contract 2 { 3[ServiceContract] 4public interface IOutputSomething 5{ 6[OperationContract] 7string GetContentData(int i); 8[OperationContract] 9string GetIpAddress(); 10} 11 } View Code
1 namespace NginxWCFTest_Service 2 { 3public class OutputSomethingService:IOutputSomething 4{ 5string threadName; 6readonly object lockObject = new object(); 7 8public string GetContentData(int i) 9{ 10lock (lockObject) 11{ 12threadName = i.ToString(0 + "-" + "我是主機:" + GetIpAddress()); 13} 14return string.Format("序列號:{0},執行緒號:{1}", i, threadName); 15} 16public string GetIpAddress() 17{ 18string AddressIP = string.Empty; 19foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) 20{ 21if (_IPAddress.AddressFamily.ToString() == "InterNetwork") 22{ 23AddressIP = _IPAddress.ToString(); 24} 25} 26return AddressIP; 27} 28} 29 } View Code
wcf服務端宿主(部署於192.168.21.129和192.168.21.130)
1 namespace NginxWCFTest_Hosting 2 { 3class Program 4{ 5static void Main(string[] args) 6{ 7ServiceHost host = new ServiceHost(typeof(OutputSomethingService)); 8host.Open(); 9//host.Opened += delegate 10//{ 11//Console.WriteLine(host.Description.Endpoints[0].Address.Uri + "已經啟動,按任意鍵終止服務!"); 12//}; 13Console.Read(); 14} 15} 16 } View Code
如果wcf基礎知識紮實的話, 宿主的程式碼很easy,我們重點需要關注的是配置資訊
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="metaBehavior"> <!-- 為避免洩漏元資料資訊, 請在部署前將以下值設定為 false --> <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" httpGetUrl="http://192.168.21.129:80/OutputSomethingService/meta"/> <!-- 要接收故障異常詳細資訊以進行除錯, 請將以下值設定為 true。在部署前設定為 false 以避免洩漏異常資訊 --> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="NginxWCFTest_Service.OutputSomethingService" behaviorConfiguration="metaBehavior"> <!--修改Binding為webHttpBinding--> <endpoint address="" binding="basicHttpBinding" contract="NginxWCFTest_Contract.IOutputSomething" > <identity> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://192.168.21.129:80/OutputSomethingService/" /> </baseAddresses> </host> </service> </services> </system.serviceModel> View Code
可以看得到服務端宿主的url埠是80,因為80是系統自帶的預設埠。一般80作為網頁伺服器的訪問埠,比如一個網站的ip地址是123.123.123.123,我們訪問的是123.123.123.123:80 只是80是預設埠可以省略。
後面針對為什麼用80埠會再一次介紹。
wcf客戶端宿主(部署於192.168.21.3)
客戶端宿主程式碼跟普通沒有區別,唯一需要注意的是配置程式碼
namespace NginxWCFTest_Client { class Program { static void Main(string[] args) { string AddressIP = string.Empty; foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (_IPAddress.AddressFamily.ToString() == "InterNetwork") { AddressIP = _IPAddress.ToString(); } } Console.WriteLine("本機IP是:" + AddressIP); using (ChannelFactory<IOutputSomething> channelFactory = new ChannelFactory<IOutputSomething>("OutputSomethingService")) { //ChannelFactory:一個建立不同型別通道的工廠,客戶端使用這些通道將訊息傳送到不同配置的服務終結點 //建立通道 IOutputSomething proxy = channelFactory.CreateChannel(); for (int i = 0; i < 20; i++) { Console.WriteLine(proxy.GetContentData(i)); } Console.Read(); } } } View Code
大家可以看到客戶端指向的地址是jackchen.com地址。這個地址是nginx虛擬機器的域名。為此,我們需要做以下事情。
主機域名處理
nginx虛擬機器主機域名處理:
主機域名的檔案路徑地址在“C:\Windows\System32\drivers\etc\hosts" 上圖紅箭頭為新增加域名,如果IE瀏覽器中輸入jackchen.com即相當於輸入http://192.168.21.128
WCF服務端主機域名處理
192.168.21.130與上圖類似,配置為192.168.21.130 jackchen.com。
wcf客戶端域名配置如下
nginx應用
上面講了WCF分散式服務的客戶端和服務端,也講了主機域名的處理。現在講講Nginx的作用和為什麼要做域名處理
nginx的基礎知識我就多講了,此處連結 http://tengine.taobao.org/book/chapter_09.html .
從上一步的主機域名解析就可以知道,WCF客戶端指向的是ngnix的虛擬機器(192.168.21.128),然後由nginx做均衡負載和備份機制管理,
未使用nginx
使用nginx
nginx部署於192.168.21.128,需要對nginx資料夾中config檔案進行配置。
配置資訊為:
#usernobody; worker_processes1; #error_loglogs/error.log; #error_loglogs/error.lognotice; #error_loglogs/error.loginfo; pidlogs/nginx.pid; events { worker_connections1024; } http { includemime.types; default_typeapplication/octet-stream; #log_formatmain'$remote_addr - $remote_user [$time_local] "$request" ' #'$status $body_bytes_sent "$http_referer" ' #'"$http_user_agent" "$http_x_forwarded_for"'; #access_loglogs/access.logmain; sendfileon; #tcp_nopushon; #keepalive_timeout0; keepalive_timeout65; #gzipon; server { listen80; server_namejackchen.com; #charset koi8-r; #access_loglogs/host.access.logmain; location / { autoindexoff;#是否開啟目錄瀏覽 root\html\Views\Home;#預設主頁目錄在nginx安裝目錄的html子目錄。 indexIndex.cshtml index.html index.htm;#起始頁 proxy_pass http://jackchen.com; } #error_page404/404.html; # redirect server error pages to the static page /50x.html # error_page500 502 503 504/50x.html; location = /50x.html { roothtml; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { #proxy_passhttp://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #roothtml; #fastcgi_pass127.0.0.1:9000; #fastcgi_indexindex.php; #fastcgi_paramSCRIPT_FILENAME/scripts$fastcgi_script_name; #includefastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { #denyall; #} } upstream linuxidc { server 127.0.0.1:8001; server 127.0.0.1:8002; server 127.0.0.1:8003; } upstream jackchen.com { server 192.168.21.129:80; server 192.168.21.130:80; } # another virtual host using mix of IP-, name-, and port-based configuration # #server { #listen8000; #listensomename:8080; #server_namesomenamealiasanother.alias; #location / { #roothtml; #indexindex.html index.htm; #} #} # HTTPS server # #server { #listen443 ssl; #server_namelocalhost; #ssl_certificatecert.pem; #ssl_certificate_keycert.key; #ssl_session_cacheshared:SSL:1m; #ssl_session_timeout5m; #ssl_ciphersHIGH:!aNULL:!MD5; #ssl_prefer_server_cipherson; #location / { #roothtml; #indexindex.html index.htm; #} #} } View Code
其中的修改點為:
upstream是配置叢集,叢集由192.168.21.129 和192.168.21.130組成
修改完了之後準備開啟nginx,下圖是進入nginx.exe所在的資料夾
接著輸入 start nginx可以啟動nginx,輸入nginx -s stop可以停止nginx,輸入nginx -s reload可以重啟nginx
效果展示
啟動兩個服務端和nginx,同時啟動客戶端,效果圖如下
關閉192.168.21.130效果圖如下