要配置nginx反向代理,首先要了解什么是反向代理。
反向代理服务器架设在服务器端,通过缓冲经常被请求的页面来缓解服务器的工作量,将客户端请求转发给内部网络上的目标服务器,并可以将请求服务器所返回的结构返回给客户端。代理服务器和目标主机一起对外表现为一个服务器。
反向的代理有两个重要的作用:
1,web网站使用反向代理除了可以防止外网对内网服务器的恶性攻击,缓存以减少服务器的压力和访问安全控制
2,进行负载均衡,将用户请求分配给多个服务器。
不多说了,直接上代码,新建一个webapi服务端项目:
using System; using System.Collections.Generic; using System.Text; namespace Demo { /// <summary> /// 用户模型。 /// </summary> public class User { /// <summary> /// 获取或者设置用户主键。 /// </summary> public int ID { get; set; } /// <summary> /// 获取或者设置用户姓名。 /// </summary> public string Name { get; set; } /// <summary> /// 获取或者设置用户账号名称。 /// </summary> public string Account { get; set; } /// <summary> /// 获取或者设置用户密码。 /// </summary> public string Password { get; set; } /// <summary> /// 获取或者设置用户的电子邮箱地址。 /// </summary> public string Email { get; set; } /// <summary> /// 获取或者设置用户角色。 /// </summary> public string Role { get; set; } /// <summary> /// 获取或者设置用户的登录时间。 /// </summary> public DateTime LoginTime { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Demo { /// <summary> /// 用户服务的接口定义。 /// </summary> public interface IUserService { /// <summary> /// 查找指定主键的用户实例对象。 /// </summary> /// <param name="id">用户的主键。</param> /// <returns>返回查找到的用户实例对象。</returns> User FindUser(int id); /// <summary> /// 获取所有用户的实例集合。 /// </summary> /// <returns>返回所有的用户实例。</returns> IEnumerable<User> UserAll(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { /// <summary> /// 实现用户服务接口的实现类型。 /// </summary> public class UserService : IUserService { private IList<User> dataList; /// <summary> /// 初始化类型的实例 /// </summary> public UserService() { dataList = new List<User>() { new User {ID=1,Name="张三",Account="5435435345",Password="4535435435",Email="4535345345", Role="Admin", LoginTime=DateTime.Now}, new User {ID=2,Name="李四",Account="5435435345",Password="5435345345",Email="543534535", Role="Admin", LoginTime=DateTime.Now.AddDays(-5) }, new User { ID = 3, Name = "王二", Account = "45354", Password = "3245345", Email = "54353455", Role = "Admin", LoginTime = DateTime.Now.AddDays(-30) }, new User { ID = 4, Name = "麻子", Account = "45354", Password = "4534535", Email = "453534534", Role = "Admin", LoginTime = DateTime.Now.AddDays(-90) }, new User { ID = 5, Name = "陈五", Account = "54353", Password = "5435345", Email = "5435345345", Role = "Admin", LoginTime = DateTime.Now.AddMinutes(-50) } }; } /// <summary> /// 查找指定主键的用户实例对象。 /// </summary> /// <param name="id">用户的主键。</param> /// <returns>返回查找到的用户实例对象。</returns> public User FindUser(int id) { return dataList.FirstOrDefault(user => user.ID == id); } /// <summary> /// 获取所有用户的实例集合。 /// </summary> /// <returns>返回所有的用户实例。</returns> public IEnumerable<User> UserAll() { return dataList; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Demo; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace NginxAPIDemo.Controllers { /// <summary> /// 用户的 API 类型。 /// </summary> [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { #region 私有字段 private readonly ILogger<ValuesController> _logger; private readonly IUserService _userService; private IConfiguration _configuration; #endregion #region 构造函数 /// <summary> /// 初始化该类型的新实例。 /// </summary> /// <param name="logger">日志记录器。</param> /// <param name="userService">用户服务接口。</param> /// <param name="configuration">配置服务。</param> public ValuesController(ILogger<ValuesController> logger, IUserService userService, IConfiguration configuration) { _logger = logger; _userService = userService; _configuration = configuration; } #endregion #region 实例方法 /// <summary> /// 获取一条记录 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet] [Route("Get")] public User Get(int id) { return _userService.FindUser(id); } /// <summary> /// 获取所有记录。 /// </summary> /// <returns></returns> [HttpGet] [Route("All")] //[Authorize] public IEnumerable<User> Get() { Console.WriteLine($"This is UsersController {this._configuration["port"]} Invoke"); return this._userService.UserAll().Select((user => new User { ID = user.ID, Name = user.Name, Account = user.Account, Password = user.Password, Email = user.Email, Role = $"{this._configuration["ip"]}:{this._configuration["port"]}", LoginTime = user.LoginTime })); ; } /// <summary> /// 超时处理 /// </summary> /// <returns></returns> [HttpGet] [Route("Timeout")] public IEnumerable<User> Timeout() { Console.WriteLine($"This is Timeout Start"); //超时设置。 Thread.Sleep(3000); Console.WriteLine($"This is Timeout End"); return this._userService.UserAll().Select((user => new User { ID = user.ID, Name = user.Name, Account = user.Account, Password = user.Password, Email = user.Email, Role = $"{this._configuration["ip"]}:{this._configuration["port"]}", LoginTime = user.LoginTime })); ; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace NginxAPIDemo { public class Program { public static void Main(string[] args) { new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddCommandLine(args)//支持命令行 .Build(); CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Demo; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NginxDemo; namespace NginxAPIDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IUserService, UserService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // 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(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
重新编译一下项目,然后模拟4个不同的api服务端,端口分别定位3100,3200,3300
找到项目实例的根目录,启动项目实例,然后定义api端口。
dotnet NginxAPIDemo.dll --urls="http://*:3100" --ip="127.0.0.1" --port=3100
通过api接口获取数据:http://localhost:3100/api/values/all
定义api接口端口3200:dotnet NginxAPIDemo.dll --urls="http://*:3200" --ip="127.0.0.1" --port=3200
通过api接口获取数据:http://localhost:3200/api/values/all
api端口3300,3400同上一样就行了。
这样服务端实例已经配置好了,下面需要下载nginx,官网: http://nginx.org/en/download.html
下载红色框内的版本,比较稳定。
下载后,解压:
配置conf文件:
打开文件配置如下:
upstream MicroService{ server localhost:3100; server localhost:3200; server localhost:3300; server localhost:3400; } server { listen 8080; server_name localhost; location / { proxy_pass http://MicroService; } }
然后启动nginx,启动命令 start nginx
然后利用nginx的8080端口来访问服务端。
第一次访问服务端ip端口是3100
第二次访问端口3200:
第三次访问3300:
第四次访问3400端口:
到这里简单的nginx反向代理就实现了。
Nginx在windows下常用命令cmd 进入Nginx解压目录 执行以下命令
start nginx : 启动nginx服务
nginx -s reload :修改配置后重新加载生效
nginx -s reopen :重新打开日志文件
nginx -t -c /path/to/nginx.conf 测试nginx配置文件是否正确
---------------------
验证配置是否正确: nginx -t
查看Nginx的版本号:nginx -V
启动Nginx:start nginx
快速停止或关闭Nginx:nginx -s stop
正常停止或关闭Nginx:nginx -s quit
配置文件修改重装载命令:nginx -s reload