NetCore微服务实战体系:Grpc+Consul 服务发现
一. 起始
去年.NetCore2.0的发布,公司决定新项目采用.NetCore开发,当作试验。但是问题在于当前公司内部使用的RPC服务为Thrift v0.9 + zookeeper版本,经过个性化定制,支持了异步,但也因为如此,这么多年来一直没有去升级,导致迁移工作很复杂(历史遗留项目太多,有各种语言的,目前只有.net体系的开发人员)。另外一点公司本身是做电商服务的,很多东西依赖了阿里的数据,阿里要求数据不能够出聚石塔,我们将所有相关的应用迁移到了聚石塔,随之问题也来了,聚石塔只开放了80端口,这么多的Thrift服务需要开放端口,机房与聚石塔之间的交互就很头疼了,如果改成http请求的话,代价以及各类成本较高。经过一段时间的调研,决定采用grpc作为新的RPC服务框架,原因有以下几点:
(1)支持多语言
(2)支持http/2,80端口可用
但是grpc需要做集群支持,也经过一段时间的研究,决定抛弃zookeeper,采用consul来作为注册中心,至于原因,有很多方面。
二. 组件Overt.Core.Grpc
为了让grpc实现集群部署,自行开发了通用组件Overt.Core.Grpc,其依赖于Grpc + Consul,代码已开源,详见github / gitee
https://github.com/overtly/core-grpc
https://gitee.com/overt/core-grpc
三. 简单介绍使用
1. Nuget包引用
-
Nuget版本:V 1.0.3
-
框架支持: Framewok 4.5 - 4.7 / NetStandard 2.0
Install-Package Overt.Core.Grpc -Version 1.0.3
2. 配置信息
(1)服务端配置信息 (NetCore / Framework)
-
NetCore配置案例 appsettings.json
{ "GrpcServer": { "Service": { "Name": "OvertGrpcServiceApp", 服务名称使用服务名称去除点 "Host": "service.g.lan", 专用注册的域名 (可选) "HostEnv": "serviceaddress", 环境变量配置(可选,同上) "Port": 10001, 端口:与端田申请 "Consul": { "Path": "dllconfigs/consulsettings.json" Consul路径,不配置将不注册,为单点项目 } } } }
-
Framework配置案例 app.config
// 添加section <configSections> <section name="grpcServer" type="Overt.Core.Grpc.GrpcServerSection, Overt.Core.Grpc" /> </configSections> // 添加节点 <grpcServer> <service name="OvertGrpcServiceApp" port="10005" host="专用注册的域名 (可选)" hostEnv="环境变量配置(可选,同上)"> <registry> <consul path="dllconfigs/Consul.config" /> </registry> </service> </grpcServer>
(2)客户端配置信息
-
NetCore
-
命名:[命名空间].dll.json 文件夹(dllconfigs)
{ "GrpcClient": { "Service": { "Name": "grpcservice", 服务名称与服务端保持一致 "MaxRetry": 0, 最大可重试次数,默认不重试 "Discovery": { "EndPoints": [ 单点模式 { "Host": "127.0.0.1", "Port": 10001 } ], "Consul": { Consul 集群 "Path": "dllconfigs/consulsettings.json" } } } } }
-
Framework
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="grpcClient" type="Overt.Core.Grpc.GrpcClientSection, Overt.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>
(3)Consul配置文件
-
NetCore
{ "ConsulServer": { "Service": { "Address": "http://consul.g.lan" // 默认8500端口 } } }
-
Framework
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="consulServer" type="Overt.Core.Grpc.ConsulServerSection, Overt.Core.Grpc"/> </configSections> <consulServer> <service address="http://consul.g.lan"></service> </consulServer> </configuration>
3. 服务端的使用
(1)NetCore
-
强制依赖注入模式
services.AddSingleton<GrpcExampleService.GrpcExampleServiceBase, GrpcExampleServiceImpl>(); Grpc服务的实现 services.AddSingleton<IHostedService, GrpcExampleHostedService>(); Grpc服务启动服务类:如下 services.AddGrpcTracer<ConsoleTracer>(); Grpc注入拦截器,继承IServerTracer using Microsoft.Extensions.Hosting; using Overt.Core.Grpc; using Overt.GrpcExample.Service.Grpc; using System.Threading; using System.Threading.Tasks; namespace Overt.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>(); }
(2)Framework 4.6
-
直接调用GrpcServiceManager来启动
using Grpc.Core; using Overt.Core.Grpc;namespace Overt.GrpcService { public class MainService { public MainService() { } public void Start(string serviceName) 启动服务 { GrpcServiceManager.Start(Library.GrpcService.BindService(new GrpcServiceImpl()), new ConsoleTracer(), (ex) => { }); } public void Stop(string serviceName) 停止服务 { GrpcServiceManager.Stop(); } public void ShutDown(string serviceName) { GrpcServiceManager.Stop(); } } }
4. 客户端使用
(1)NetCore
-
强制依赖注入模式
-
配置文件默认使用 [命名空间].dll.json 可通过vs.menu工具生成nuget包
-
注入中直接调用如下
// 注入Grpc客户端 services.AddGrpcClient(); // 自定义配置文件 / 默认使用命名空间.dll.json services.Configure<GrpcClientOptions<GrpcExampleServiceClient>>((cfg) => { cfg.JsonFile = "dllconfig/Overt.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" });
(2)Framework
-
客户端代理类,编译在Dll中,类似于ThriftProxy,源码如下,可忽略
using Overt.Core.Grpc; using System; using System.IO; namespace Overt.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/Overt.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]