擴展gRPC支持consul服務發現和Polly策略

来源:https://www.cnblogs.com/hubro/archive/2020/03/23/12537409.html
-Advertisement-
Play Games

gRPC由於需要用工具生成代碼實現,可開發性不是很高,在擴展這方面不是很友好 最近研究了下,進行了擴展,不需要額外的工具生成,直接使用預設Grpc.Tools生成的代理類即可 相關源碼在文章底部 客戶端目標: 能配置consul地址和服務名稱,在調用client時能正確請求到真實的服務地址 在調用方 ...


gRPC由於需要用工具生成代碼實現,可開發性不是很高,在擴展這方面不是很友好

最近研究了下,進行了擴展,不需要額外的工具生成,直接使用預設Grpc.Tools生成的代理類即可

相關源碼在文章底部

客戶端目標:

  • 能配置consul地址和服務名稱,在調用client時能正確請求到真實的服務地址
  • 在調用方法時,能使用Polly策略重試,超時,和熔斷

查看gRPC生成的代碼,可以看到Client實例化有有兩個構造方法,以測試為例

      /// <summary>Creates a new client for Greeter</summary>
      /// <param name="channel">The channel to use to make remote calls.</param>
      public GreeterClient(grpc::ChannelBase channel) : base(channel)
      {
      }
      /// <summary>Creates a new client for Greeter that uses a custom <c>CallInvoker</c>.</summary>
      /// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
      public GreeterClient(grpc::CallInvoker callInvoker) : base(callInvoker)
      {
      }

1.可傳入一個ChannelBase實例化

2.可傳入一個CallInvoker實例化

Channel可實現為

Channel CreateChannel(string address)
        {
            var channelOptions = new List<ChannelOption>()
                    {
                        new ChannelOption(ChannelOptions.MaxReceiveMessageLength, int.MaxValue),
                        new ChannelOption(ChannelOptions.MaxSendMessageLength, int.MaxValue),
                    };
            var channel = new Channel(address, ChannelCredentials.Insecure, channelOptions);
            return channel;
        }

在這裡,可以從consul地址按服務名獲取真實的服務地址,生成Channel

 

CallInvoker為一個抽象類,若要對方法執行過程干預,則需要重寫這個方法,大致實現為

public class GRpcCallInvoker : CallInvoker
    {
        public readonly Channel Channel;
        public GRpcCallInvoker(Channel channel)
        {
            Channel = GrpcPreconditions.CheckNotNull(channel); 
        }

        public override TResponse BlockingUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            return Calls.BlockingUnaryCall(CreateCall(method, host, options), request);
        }

        public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            return Calls.AsyncUnaryCall(CreateCall(method, host, options), request);
        }

        public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            return Calls.AsyncServerStreamingCall(CreateCall(method, host, options), request);
        }

        public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
        {
            return Calls.AsyncClientStreamingCall(CreateCall(method, host, options));
        }

        public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
        {
            return Calls.AsyncDuplexStreamingCall(CreateCall(method, host, options));
        }

        protected virtual CallInvocationDetails<TRequest, TResponse> CreateCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
            where TRequest : class 
            where TResponse : class
        {
            return new CallInvocationDetails<TRequest, TResponse>(Channel, method, host, options);
        }
    }

這裡可以傳入上面創建的Channel,在CreateCall方法里,則可以對調用方法進行控制

完整實現為

public class GRpcCallInvoker : CallInvoker
    {
        GrpcClientOptions _options;
        IGrpcConnect _grpcConnect;
        public GRpcCallInvoker(IGrpcConnect grpcConnect)
        {
            _options = grpcConnect.GetOptions();
            _grpcConnect = grpcConnect;
        }

        public override TResponse BlockingUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            return Calls.BlockingUnaryCall(CreateCall(method, host, options), request);
        }

        public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            return Calls.AsyncUnaryCall(CreateCall(method, host, options), request);
        }

        public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            return Calls.AsyncServerStreamingCall(CreateCall(method, host, options), request);
        }

        public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
        {
            return Calls.AsyncClientStreamingCall(CreateCall(method, host, options));
        }

        public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
        {
            return Calls.AsyncDuplexStreamingCall(CreateCall(method, host, options));
        }

        protected virtual CallInvocationDetails<TRequest, TResponse> CreateCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
            where TRequest : class
            where TResponse : class
        {
            var methodName = $"{method.ServiceName}.{method.Name}";
            var key = methodName.Substring(methodName.IndexOf(".") + 1).ToLower();
            var a = _options.MethodPolicies.TryGetValue(key, out PollyAttribute methodPollyAttr);
            if (!a)
            {
                _options.MethodPolicies.TryGetValue("", out methodPollyAttr);
            }
            CallOptions options2;
            //重寫header
            if (options.Headers != null)
            {
                options2 = options;
            }
            else
            {
                options2 = new CallOptions(_grpcConnect.GetMetadata(), options.Deadline, options.CancellationToken);
            }

            var pollyData = PollyExtension.Invoke(methodPollyAttr, () =>
            {
                var callRes = new CallInvocationDetails<TRequest, TResponse>(_grpcConnect.GetChannel(), method, host, options2);
                return new PollyExtension.PollyData<CallInvocationDetails<TRequest, TResponse>>() { Data = callRes };
            }, $"{methodName}");
            var response = pollyData.Data;
            if (!string.IsNullOrEmpty(pollyData.Error))
            {
                throw new Exception(pollyData.Error);
            }
            return response;
            //return new CallInvocationDetails<TRequest, TResponse>(Channel.Invoke(), method, host, options2);
        }
    }

 

其中傳入了PollyAttribute,由PollyExtension.Invoke來完成Polly策略的實現,具體代碼可在源碼里找到

從上面代碼可以看到,CallInvoker里可以傳入了IGrpcConnect,由方法IGrpcConnect.GetChannel()獲取Channel

Client實例化

.net FrameWork實現為

     public T GetClient<T>()
        {
            var a = instanceCache.TryGetValue(typeof(T), out object instance);
            if (!a)
            {
                var grpcCallInvoker = new GRpcCallInvoker(this);
                instance = System.Activator.CreateInstance(typeof(T), grpcCallInvoker);
                instanceCache.TryAdd(typeof(T), instance);
            }
            return (T)instance;
        }

core則簡單點,直接註入實現

var client = provider.GetService<Greeter.GreeterClient>();

服務端註冊

和其它服務註冊一樣,填入正確的服務地址和名稱就行了,但是在Check里得改改,gRPC的健康檢查參數是不同的,並且在consul客戶端里沒有這個參數,得自已寫

以下代碼是我封裝過的,可查看源碼

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();
                endpoints.MapGrpcService<HealthCheckService>();
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });

            //註冊服務
            var consulClient = new CRL.Core.ConsulClient.Consul("http://localhost:8500");
            var info = new CRL.Core.ConsulClient.ServiceRegistrationInfo
            {
                Address = "127.0.0.1",
                Name = "grpcServer",
                ID = "grpcServer1",
                Port = 50001,
                Tags = new[] { "v1" },
                Check = new CRL.Core.ConsulClient.CheckRegistrationInfo()
                {
                    GRPC = "127.0.0.1:50001",
                    Interval = "10s",
                    GRPCUseTLS = false,
                    DeregisterCriticalServiceAfter = "90m"
                }
            };
            consulClient.DeregisterService(info.ID);
            var a = consulClient.RegisterService(info);

        }

 客戶端完整封裝代碼為

core擴展方法,設置GrpcClientOptions來配置consul地址和Polly策略,直接註入了Client類型

同時添加了統一header傳遞,使整個服務都能用一個頭髮送請求,不用再在方法後面跟參數

public static class GrpcExtensions
    {
        public static void AddGrpcExtend(this IServiceCollection services, Action<GrpcClientOptions> setupAction, params Assembly[] assemblies)
        {
            services.Configure(setupAction);
            services.AddSingleton<IGrpcConnect, GrpcConnect>();
            services.AddScoped<CallInvoker, GRpcCallInvoker>();
            foreach (var assembyle in assemblies)
            {
                var types = assembyle.GetTypes();
                foreach (var type in types)
                {
                    if(typeof(ClientBase).IsAssignableFrom(type))
                    {
                        services.AddSingleton(type);
                    }
                }
            }
        }
    }
 class Program
    {
        static IServiceProvider provider;
        static Program()
        {
            var builder = new ConfigurationBuilder();

            var configuration = builder.Build();

            var services = new ServiceCollection();
            services.AddSingleton<IConfiguration>(configuration);
            services.AddOptions();

            services.AddGrpcExtend(op =>
            {
                op.Host = "127.0.0.1";
                op.Port = 50001;
                op.UseConsulDiscover("http://localhost:8500", "grpcServer");//使用consul服務發現
                op.AddPolicy("Greeter.SayHello", new CRL.Core.Remoting.PollyAttribute() { RetryCount = 3 });//定義方法polly策略
            }, System.Reflection.Assembly.GetExecutingAssembly());

            provider = services.BuildServiceProvider();
        }


        static void Main(string[] args)
        {            
            //設置允許不安全的HTTP2支持
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            var grpcConnect = provider.GetService<IGrpcConnect>();
            //認證
            //https://www.cnblogs.com/stulzq/p/11897628.html
            var token = "";
            var headers = new Metadata { { "Authorization", $"Bearer {token}" } };
            grpcConnect.SetMetadata(headers);


        label1:
            var client = provider.GetService<Greeter.GreeterClient>();
            var reply = client.SayHello(
                new HelloRequest { Name = "test" });
            Console.WriteLine("Greeter 服務返回數據: " + reply.Message);

            Console.ReadLine();
            goto label1;
        }
    }

 

運行服務端,結果為

可以看到服務註冊成功,狀態檢查也成功

運行客戶端

客戶端正確調用並返回了結果

項目源碼:

https://github.com/CRL2020/CRL.NetStandard/tree/master/Grpc

除了gRPC實現了服務發現和Polly策略,本框架對API代理,動態API,RPC也一起實現了

API代理測試
https://github.com/CRL2020/CRL.NetStandard/tree/master/DynamicWebApi/ApiProxyTest

動態API測試

https://github.com/CRL2020/CRL.NetStandard/tree/master/DynamicWebApi/DynamicWebApiClient

RCP測試

https://github.com/CRL2020/CRL.NetStandard/tree/master/RPC/RPCClient

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ASP.NET Core引入了Options模式,使用類來表示相關的設置組。簡單的來說,就是用強類型的類來表達配置項,這帶來了很多好處。 初學者會發現這個框架有3個主要的面向消費者的介面:IOptions ...
  • 前言 回顧上一篇文章《使用Swagger做Api文檔 》,文中介紹了在.net core 3.1中,利用Swagger輕量級框架,如何引入程式包,配置服務,註冊中間件,一步一步的實現,最終實現生產自動生產API介面說明文檔。文中結尾也留下了一個讓大家思考的問題。在這裡,我們重新回顧一下這幾個問題 1 ...
  • 視頻教程(使用+實現原理):https://share.weiyun.com/57HKopT 建議直接看視頻 源碼地址:https://github.com/bxjg1987/abpGeneralModules 庫版本.net core 3.1 我的abp版本:abp5.3 .net core 3. ...
  • 常見數據類型 C 的類型一般分為 值類型 、 引用類型 兩大類型。 值類型的實例存放在棧中,引用類型會在棧中放置一個指針指向堆中的某一塊內容。 C 為我們內置了幾個數據類型供我們使用: |關鍵詞簡寫|對應的類全稱(點擊可以查看對應的API)|值範圍|說明| |: :|: |: |: | | bool ...
  • 一、C#基本認識 1.1.區分.net與C# .net:一般指.Net Framework框架,是Microsoft開發的一個平臺。 代碼庫 定義了基本的類型,也稱為通用類型系統(Common Type System,CTS) 包含.net公共語言運行庫(Common Language Runtim ...
  • 基本思路是把原來的WindowStyle設置為None,然後自己弄一個標題欄 一、xmal 二、後臺代碼(幾個事件) ...
  • 一、引言 MSMQ全稱MicroSoft Message Queue,微軟消息隊列,是在多個不同的應用之間實現相互通信的一種非同步傳輸模式,相互通信的應用可以分佈於同一臺機器上,也可以分佈於相連的網路空間中的任一位置。它的實現原理是:消息的發送者把自己想要發送的信息放入一個容器中(我們稱之為Messa ...
  • return (from merchantsInfo in base.GetIQueryable(x => x.IsLogicDelete == false && x.FID != fid) join userAccount in UserAccountDal.GetIQueryable(x => ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...