一. 起始
去年.NetCore2.0的发布,公司决定新项目采用.NetCore开发,当作试验。但是问题在于当前公司内部使用的RPC服务为Thrift v0.9 + zookeeper版本,经过个性化定制,支持了异步,但也因为如此,这么多年来一直没有去升级,导致迁移工作很复杂(历史遗留项目太多,有各种语言的,目前只有.net体系的开发人员)。另外一点公司本身是做电商服务的,很多东西依赖了阿里的数据,阿里要求数据不能够出聚石塔,我们将所有相关的应用迁移到了聚石塔,随之问题也来了,聚石塔只开放了80端口,这么多的Thrift服务需要开放端口,机房与聚石塔之间的交互就很头疼了,如果改成http请求的话,代价以及各类成本较高。经过一段时间的调研,决定采用grpc作为新的RPC服务框架,原因有以下几点:
(1)支持多语言
(2)支持http/2,80端口可用
但是grpc需要做集群支持,也经过一段时间的研究,决定抛弃zookeeper,采用consul来作为注册中心,至于原因,有很多方面。
二. 组件Sodao.Core.Grpc
为了让grpc实现集群部署,自行开发了通用组件Sodao.Core.Grpc,其依赖于Grpc + Consul,代码已开源,详见github
https://github.com/mojinxun/sodao.core.grpc
三. 简单介绍使用
1. Nuget包引用
- Nuget版本:V 1.0.0
- 框架支持: Framewok 4.5 - 4.7 / NetStandard 2.0
Install-Package Sodao.Core.Grpc -Version 1.0.0
2. 配置信息
(1)服务端配置信息 (NetCore / Framework)
- NetCore配置案例 appsettings.json
{ ?"GrpcServer": { ???"Service": { ?????"Name": "SodaoGrpcServiceApp", ???????????????????服务名称使用服务名称去除点 ?????"Host": "service.g.lan", ?????????????????????????专用注册的域名 (可选) ?????"HostEnv": "serviceaddress", ?????????????????????环境变量配置(可选,同上) ?????"Port": 10001, ???????????????????????????????????端口:与端田申请 ?????"Consul": { ???????"Path": "dllconfigs/consulsettings.json" ???????Consul路径,不配置将不注册,为单点项目 ?????} ???} ?}}
- Framework配置案例 app.config
// 添加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>
(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="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>
(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="Sodao.Core.Grpc.ConsulServerSection, Sodao.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 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); ???????} ???}}
- 实现类写法
// 原因:服务启动的时候是一个单例,那么所有服务之下的全部是单实例,而数据层需要使用多实例// 只注入 IServiceProviderIServiceProvider _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 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(); ???????} ???}}
4. 客户端使用
(1)NetCore
- 强制依赖注入模式
- 配置文件默认使用 [命名空间].dll.json 可通过vs.menu工具生成nuget包
- 注入中直接调用如下
// 注入Grpc客户端services.AddGrpcClient();// 自定义配置文件 / 默认使用命名空间.dll.jsonservices.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" });
(2)Framework
- 客户端代理类,编译在Dll中,类似于ThriftProxy,源码如下,可忽略
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]
NetCore服务虚拟化01(集群组件Sodao.Core.Grpc)
原文地址:https://www.cnblogs.com/mojinxun/p/10050303.html