前言
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都需要這樣設置。