一. 起始git
去年.NetCore2.0的發佈,公司決定新項目採用.NetCore開發,看成試驗。可是問題在於當前公司內部使用的RPC服務爲Thrift v0.9 + zookeeper版本,通過個性化定製,支持了異步,但也由於如此,這麼多年來一直沒有去升級,致使遷移工做很複雜(歷史遺留項目太多,有各類語言的,目前只有.net體系的開發人員)。另一點公司自己是作電商服務的,不少東西依賴了阿里的數據,阿里要求數據不可以出聚石塔,咱們將全部相關的應用遷移到了聚石塔,隨之問題也來了,聚石塔只開放了80端口,這麼多的Thrift服務須要開放端口,機房與聚石塔之間的交互就很頭疼了,若是改爲http請求的話,代價以及各種成本較高。通過一段時間的調研,決定採用grpc做爲新的RPC服務框架,緣由有如下幾點:github
(1)支持多語言json
(2)支持http/2,80端口可用app
可是grpc須要作集羣支持,也通過一段時間的研究,決定拋棄zookeeper,採用consul來做爲註冊中心,至於緣由,有不少方面。框架
二. 組件Sodao.Core.Grpc異步
爲了讓grpc實現集羣部署,自行開發了通用組件Sodao.Core.Grpc,其依賴於Grpc + Consul,代碼已開源,詳見github ide
https://github.com/mojinxun/core-grpc工具
https://gitee.com/overt/core-grpcspa
三. 簡單介紹使用.net
1. Nuget包引用
Install-Package Sodao.Core.Grpc -Version 1.0.0
{ "GrpcServer": { "Service": { "Name": "SodaoGrpcServiceApp", 服務名稱使用服務名稱去除點 "Host": "service.g.lan", 專用註冊的域名 (可選) "HostEnv": "serviceaddress", 環境變量配置(可選,同上) "Port": 10001, 端口:與端田申請 "Consul": { "Path": "dllconfigs/consulsettings.json" Consul路徑,不配置將不註冊,爲單點項目 } } } }
// 添加section <configSections> <section name="grpcServer" type="Sodao.Core.Grpc.GrpcServerSection, Sodao.Core.Grpc" /> </configSections> // 添加節點 <grpcServer> <service name="SodaoGrpcServiceApp" port="10005" host="專用註冊的域名 (可選)" hostEnv="環境變量配置(可選,同上)"> <registry> <consul path="dllconfigs/Consul.config" /> </registry> </service> </grpcServer>
{ "GrpcClient": { "Service": { "Name": "grpcservice", 服務名稱與服務端保持一致 "MaxRetry": 0, 最大可重試次數,默認不重試 "Discovery": { "EndPoints": [ 單點模式 { "Host": "127.0.0.1", "Port": 10001 } ], "Consul": { Consul 集羣 "Path": "dllconfigs/consulsettings.json" } } } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="grpcClient" type="Sodao.Core.Grpc.GrpcClientSection, Sodao.Core.Grpc"/> </configSections> <grpcClient> <service name="" maxRetry="0"> <discovery> <server> <endpoint host="" port=""></endpoint> <endpoint host="" port=""></endpoint> </server> <consul path="dllconfigs/Consul.config"></consul> </discovery> </service> </grpcClient> </configuration>
{ "ConsulServer": { "Service": { "Address": "http://consul.g.lan" // 默認8500端口 } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="consulServer" type="Sodao.Core.Grpc.ConsulServerSection, Sodao.Core.Grpc"/> </configSections> <consulServer> <service address="http://consul.g.lan"></service> </consulServer> </configuration>
services.AddSingleton<GrpcExampleService.GrpcExampleServiceBase, GrpcExampleServiceImpl>(); Grpc服務的實現 services.AddSingleton<IHostedService, GrpcExampleHostedService>(); Grpc服務啓動服務類:以下 services.AddGrpcTracer<ConsoleTracer>(); Grpc注入攔截器,繼承IServerTracer using Microsoft.Extensions.Hosting; using Sodao.Core.Grpc; using Sodao.GrpcExample.Service.Grpc; using System.Threading; using System.Threading.Tasks; namespace Sodao.GrpcService.App { public class GrpcService : IHostedService { GrpcExampleService.GrpcExampleServiceBase _grpcServiceBase; IServerTracer _tracer; public GrpcService(GrpcExampleService.GrpcExampleServiceBase serviceBase, IServerTracer tracer) 依賴注入Grpc服務基礎類 { _serviceBase = serviceBase; _tracer = tracer; } public Task StartAsync(CancellationToken cancellationToken) { return Task.Factory.StartNew(() => { GrpcServiceManager.Start(GrpcExampleService.BindService(_serviceBase), _tracer); }, cancellationToken); } public Task StopAsync(CancellationToken cancellationToken) { return Task.Factory.StartNew(() => { GrpcServiceManager.Stop(); }, cancellationToken); } } }
// 緣由:服務啓動的時候是一個單例,那麼全部服務之下的所有是單實例,而數據層須要使用多實例 // 只注入 IServiceProvider IServiceProvider _provider; public GrpcExampleServiceImpl(IServiceProvider provider) { _provider = provider; } // 其餘利用provider即時獲取 using(var scope = _provider.CreateSocpe()) { var _userService = scope.ServiceProvider.GetService<IUserService>(); }
using Grpc.Core; using Sodao.Core.Grpc; using Sodao.Log; using System; namespace Sodao.GrpcService { public class MainService { public MainService() { } public void Start(string serviceName) 啓動服務 { GrpcServiceManager.Start(Library.GrpcService.BindService(new GrpcServiceImpl()), new ConsoleTracer(), (ex) => { LogHelper.Info("", ex); }); } public void Stop(string serviceName) 中止服務 { GrpcServiceManager.Stop(); } public void ShutDown(string serviceName) { GrpcServiceManager.Stop(); } } }
// 注入Grpc客戶端 services.AddGrpcClient(); // 自定義配置文件 / 默認使用命名空間.dll.json services.Configure<GrpcClientOptions<GrpcExampleServiceClient>>((cfg) => { cfg.JsonFile = "dllconfig/Sodao.GrpcExample.Service.Grpc.dll.json"; // 可不傳遞 }); // 獲取注入的對象 IGrpcClient<GrpcExampleServiceClient> _grpcClient; public IndexModel(IGrpcClient<GrpcExampleServiceClient> grpcClient) { _grpcClient = grpcClient; } var res = _grpcClient.Client.Ask(new Service.Grpc.AskRequest() { Key = "abc" });
using Sodao.Core.Grpc; using System; using System.IO; namespace Sodao.GrpcService.Generate { public class ClientManager { private volatile static GrpcService.GrpcServiceClient _Client = null; private static readonly object lockHelper = new object(); public static IClientTracer Tracer { get; set; } = default(IClientTracer); /// <summary> /// 單例實例 /// </summary> public static GrpcService.GrpcServiceClient Instance { get { if (_Client == null) { lock (lockHelper) { try { var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dllconfigs/Sodao.GrpcService.Library.dll.config"); _Client = GrpcClientManager<GrpcService.GrpcServiceClient>.Get(configPath, Tracer); } catch (Exception ex) { throw new Exception($"{ex.InnerException?.InnerException?.Message}"); } } } return _Client; } } } }
ClientManager.Instance.[Method]