1. 程式人生 > >NetCore服務虛擬化01(集群組件Sodao.Core.Grpc)

NetCore服務虛擬化01(集群組件Sodao.Core.Grpc)

user service() 引用 http請求 一段時間 prope 沒有 pri ==

一. 起始

去年.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);
        }
    }
}


  • 實現類寫法
// 原因:服務啟動的時候是一個單例,那麽所有服務之下的全部是單實例,而數據層需要使用多實例

// 只註入 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 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.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" });

(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)