前言
一直以來對於.NETCore微服務相關的技術棧都處於一個淺嘗輒止的了解階段,在現實工作中也對於微服務也一直沒有使用的業務環境,所以一直也沒有整合過一個完整的基於.NETCore技術棧的微服務項目。正好由於最近剛好辭職,有了時間可以寫寫自己感興趣的東西,所以在此想把自己了解的微服務相關的概念和技術框架使用實現記錄在一個完整的工程中,由於本人技術有限,所以錯誤的地方希望大家指出。\
什么是Api網關
由於微服務把具體的業務分割成單獨的服務,所以如果直接將每個服務都與調用者直接,那么維護起來將相當麻煩與頭疼,Api網關擔任的角色就是整合請求並按照路由規則轉發至服務的實例,並且由於所有所有請求都經過網關,那么網關還可以承擔一系列宏觀的攔截功能,例如安全認證,日志,熔斷
為什么需要Api網關
因為Api網關可以提供安全認證,日志,熔斷相關的宏觀攔截的功能,也可以屏蔽多個下游服務的內部細節
有哪些有名的Api網關項目
- Zuul Spring Cloud 集成
- Kong 一款lua輕量級網關項目
- Ocelot .NETCore網關項目
Ocelot使用
1.通過Nuget安裝Ocelot
2.准備並編輯Ocelot配置信息
Ocelot.json
{
"ReRoutes": [
// Auth
{
"UpstreamPathTemplate": "/auth/{action}", // 上游請求路徑模板
"UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE" ], // 上游請求方法
"ServiceName": "Auth", // 服務名稱
"UseServiceDiscovery": true, // 是否使用服務發現
"DownstreamPathTemplate": "/connect/{action}", // 下游匹配路徑模板
"DownstreamScheme": "http", // 下游請求
"LoadBalancerOptions": { // 負載均衡配置
"Type": "RoundRobin"
}
//,
// 如果不采用服務發現需要指定下游host
//"DownstreamHostAndPorts": [
// {
// "Host": "10.0.1.10",
// "Port": 5000
// },
// {
// "Host": "10.0.1.11",
// "Port": 5000
// }
//]
}
],
"GlobalConfiguration": { // 全局配置信息
"BaseUrl": "http://localhost:5000", // 請求 baseurl
"ServiceDiscoveryProvider": { //服務發現提供者
"Host": "106.53.199.185",
"Port": 8500,
"Type": "Consul" // 使用Consul
}
}
}
3.添加Ocelot json文件到項目中
將Config目錄下的ocelot.json添加到項目中
4.在網關項目中 StartUp ConfigService中添加Ocelot的服務,在Configure中添加Ocelot的中間件(由於我這里使用了Consul作為服務發現,所以需要添加Consul的依賴的服務AddConsul,如果不需要服務發現的話可以不用添加)
5.將需要發現的服務通過代碼在啟動時注冊到Consul中
我這里自己封裝了一個注冊服務的擴展(寫的比較隨意沒有在意細節)
appsettings.json 中添加注冊服務配置信息
"ServiceOptions": {
"ServiceIP": "localhost",
"ServiceName": "Auth",
"Port": 5800,
"HealthCheckUrl": "/api/health",
"ConsulOptions": {
"Scheme": "http",
"ConsulIP": "localhost",
"Port": 8500
}
}
擴展代碼 ConsulExtensions(注意:3.1中 IApplicationLifetime已廢棄 所以使用的是IHostApplicationLifetime 作為程序生命周期注入的方式)
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace ForDotNet.Common.Consul.Extensions
{
/// <summary>
/// 服務配置信息
/// </summary>
public class ServiceOptions
{
/// <summary>
/// 服務ip
/// </summary>
public string ServiceIP { get; set; }
/// <summary>
/// 服務名稱
/// </summary>
public string ServiceName { get; set; }
/// <summary>
/// 協議類型http or https
/// </summary>
public string Scheme { get; set; } = "http";
/// <summary>
/// 端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 健康檢查接口
/// </summary>
public string HealthCheckUrl { get; set; } = "/api/values";
/// <summary>
/// 健康檢查間隔時間
/// </summary>
public int HealthCheckIntervalSecond { get; set; } = 10;
/// <summary>
/// consul配置信息
/// </summary>
public ConsulOptions ConsulOptions { get; set; }
}
/// <summary>
/// consul配置信息
/// </summary>
public class ConsulOptions
{
/// <summary>
/// consul ip
/// </summary>
public string ConsulIP { get; set; }
/// <summary>
/// consul 端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 協議類型http or https
/// </summary>
public string Scheme { get; set; } = "http";
}
/// <summary>
/// consul注冊客戶端信息
/// </summary>
public class ConsulClientInfo
{
/// <summary>
/// 注冊信息
/// </summary>
public AgentServiceRegistration RegisterInfo { get; set; }
/// <summary>
/// consul客戶端
/// </summary>
public ConsulClient Client { get; set; }
}
/// <summary>
/// consul擴展(通過配置文件配置)
/// </summary>
public static class ConsulExtensions
{
private static readonly ServiceOptions serviceOptions = new ServiceOptions();
/// <summary>
/// 添加consul
/// </summary>
public static void AddConsulServiceDiscovery(this IServiceCollection services)
{
var config = services.BuildServiceProvider().GetService<IConfiguration>();
config.GetSection("ServiceOptions").Bind(serviceOptions);
//config.Bind(serviceOptions);
if (serviceOptions == null)
{
throw new Exception("獲取服務注冊信息失敗!請檢查配置信息是否正確!");
}
Register(services);
}
/// <summary>
/// 添加consul(通過配置opt對象配置)
/// </summary>
/// <param name="app"></param>
/// <param name="life">引用生命周期</param>
/// <param name="options">配置參數</param>
public static void AddConsulServiceDiscovery(this IServiceCollection services, Action<ServiceOptions> options)
{
options.Invoke(serviceOptions);
Register(services);
}
/// <summary>
/// 注冊consul服務發現
/// </summary>
/// <param name="app"></param>
/// <param name="life"></param>
public static void UseConsulServiceDiscovery(this IApplicationBuilder app, IHostApplicationLifetime life)
{
var consulClientInfo = app.ApplicationServices.GetRequiredService<ConsulClientInfo>();
if (consulClientInfo != null)
{
life.ApplicationStarted.Register( () =>
{
consulClientInfo.Client.Agent.ServiceRegister(consulClientInfo.RegisterInfo).Wait();
});
life.ApplicationStopping.Register( () =>
{
consulClientInfo.Client.Agent.ServiceDeregister(consulClientInfo.RegisterInfo.ID).Wait();
});
}
else
{
throw new NullReferenceException("未找到相關consul客戶端信息!");
}
}
private static void Register(this IServiceCollection services)
{
if (serviceOptions == null)
{
throw new Exception("獲取服務注冊信息失敗!請檢查配置信息是否正確!");
}
if (serviceOptions.ConsulOptions == null)
{
throw new ArgumentNullException("請檢查是否配置Consul信息!");
}
string consulAddress = $"{serviceOptions.ConsulOptions.Scheme}://{serviceOptions.ConsulOptions.ConsulIP}:{serviceOptions.ConsulOptions.Port}";
var consulClient = new ConsulClient(opt =>
{
opt.Address = new Uri(consulAddress);
});
var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10), // 服務啟動多久后注冊
Interval = TimeSpan.FromSeconds(serviceOptions.HealthCheckIntervalSecond), // 間隔
HTTP = $"{serviceOptions.Scheme}://{serviceOptions.ServiceIP}:{serviceOptions.Port}{serviceOptions.HealthCheckUrl}",
Timeout = TimeSpan.FromSeconds(10)
};
var registration = new AgentServiceRegistration()
{
Checks = new[] { httpCheck },
ID = Guid.NewGuid().ToString(),
Name = serviceOptions.ServiceName,
Address = serviceOptions.ServiceIP,
Port = serviceOptions.Port,
};
services.AddSingleton(new ConsulClientInfo()
{
Client = consulClient,
RegisterInfo = registration
});
}
}
}
6.啟動運行
- 啟動consul
- 啟動 Auth,Gateway項目
- 通過網關項目訪問Auth
啟動Consul
為了方便演示這里是以開發者啟動的consul
在consul.exe的目錄下執行
consul agent -dev -ui // 開發者模式運行帶ui
啟動 Auth,Gateway項目
啟動項目和可以發現我的們Auth服務已經注冊進來了
通過網關訪問Auth
我們這里訪問 http://localhost:5000/auth/token 獲取token
我們可以看到網關項目接收到了請求並在控制台中打印出以下信息
然后在Auth項目中的控制台中可以看到已經成功接收到了請求並響應