ASP.NET Core 3.0 gRPC 配置使用HTTP


前言

gRPC是基於http/2,是同時支持https和http協議的,我們在gRPC實際使用中,在內網通訊場景下,更多的是走http協議,達到更高的效率,下面介紹如何在 .NET Core 3.0 中如何為gRPC配置http。

服務端配置Kestrel

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureKestrel(options =>
            {
                // Setup a HTTP/2 endpoint without TLS.
                options.ListenLocalhost(5000, o => o.Protocols =
                    HttpProtocols.Http2);
            });
            webBuilder.UseStartup<Startup>();
        });

主要是這句話 Protocols = HttpProtocols.Http2 讓kestrel支持無 tls http/2

在最新的asp.net core 中,http端口默認已經配置了,所以服務端配置不是必須的

客戶端

客戶端需要在創建 grpc 調用以前設置:

AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

示例:

AppContext.SetSwitch(
    "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var channel = GrpcChannel.ForAddress("http://localhost:5000");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(
    new HelloRequest { Name = "曉晨" });
Console.WriteLine("調用Greeter服務 : " + reply.Message);

客戶端跨語言調用非tls gRPC都需要這樣設置。

相關資料: https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.0&WT.mc_id=DT-MVP-5003133


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM