一.实现前的准备
- 以下是实现简单负载均衡的思路,图中的服务器均为虚拟机
- 三台Linux服务器,一台用作Nginx负载均衡(192.168.254.139),另外两台用作Asp.Net Core应用程序承载的服务器(192.168.254.140,192.168.254.141)
- 一台用作于Client的Windows服务器。
二.环境搭建
1.Asp.Net Core程序
就是一个新建的空web应用程序,然后修改了下Startup的中间件,分别部署到2台Ubuntu上。
public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application,visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app,IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { //await context.Response.WriteAsync("this is first web application"); await context.Response.WriteAsync("this is second web application"); }); } }
2.配置Nginx服务器
upstream cluster.com{ server 192.168.254.140 weight=1; server 192.168.254.141 weight=1; } server { listen 80 default_server; # listen [::]:80 default_server deferred; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don‘t use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.PHP to the list if you are using PHP index index.html index.htm index.Nginx-debian.html; server_name _example.com *.example.com; location / { proxy_pass http://cluster.com; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # First attempt to serve request as file,then # as directory,then fall back to displaying a 404. try_files $uri $uri/ =404; } # pass PHP scripts to FastCGI server # #location ~ \.PHP$ { # include snippets/fastcgi-PHP.conf; # # # With PHP-fpm (or other unix sockets): # fastcgi_pass unix:/var/run/PHP/PHP7.0-fpm.sock; # # With PHP-cgi (or other tcp sockets): # fastcgi_pass 127.0.0.1:9000; #} # deny access to .htaccess files,if Apache‘s document root # concurs with Nginx‘s one # #location ~ /\.ht { # deny all; #} }
2.Client控制台应用程序
class Program { static void Main(string[] args) { HttpClient httpClient = new HttpClient(); for (int i = 0; i < 1000; i++) { string result = httpClient.GetStringAsync("http://192.168.254.139").Result; Console.WriteLine(result); } Console.ReadKey(); } }
结果如下: