asp.net core 3.0中Grpc.AspNetCore.Server帶來了什麼

Celery發表於2019-05-25

Grpc.AspNetCore.Server帶來了什麼

dotnet core 3.0在公佈的時候有一個重要的feature, 那就是支援gRPC. gRPC作為一個nuget包早就能工作在Net Core下面. 那dotnet core 3.0中對gRPC的支援到底實現了哪些功能呢?

在.net core 2.2中Host Grpc伺服器

參考上一篇文章, 使用protoc或者Visual Studio編輯生成了C#的伺服器端程式碼. 實現伺服器端具體的邏輯:

class GreeterImpl : Greeter.GreeterBase
{
    // Server side handler of the SayHello RPC
    public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
    }

    // Server side handler for the SayHelloAgain RPC
    public override Task<HelloReply> SayHelloAgain(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply { Message = "Hello again " + request.Name });
    }
}
複製程式碼

在Console專案中Host gRPC服務:

public static void Main(string[] args)
{
    Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

    var client = new Greeter.GreeterClient(channel);
    String user = "you";

    var reply = client.SayHello(new HelloRequest { Name = user });
    Console.WriteLine("Greeting: " + reply.Message);

    var secondReply = client.SayHelloAgain(new HelloRequest { Name = user });
    Console.WriteLine("Greeting: " + secondReply.Message);

    channel.ShutdownAsync().Wait();
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}
複製程式碼

Console專案可以考慮作為Windows服務. 或者在asp.net core中採用IHostedService方式Host. 可參考: Background tasks with hosted services in ASP.NET Core

在.net core 3.0中使用Grpc.AspNetCore.Server Host gRPC

在.net core 3.0中可以直接支援gRPC, 專案的建立模版中可以直接選擇gRPC, 生成專案的startup.cs中可以找到看到grpc已經作為預設的middleware新增:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
    }

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

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            // 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
            endpoints.MapGrpcService<GreeterService>();
        });
    }
}
複製程式碼

這也意味者該專案中還可以新增其他的中介軟體比如說MVC Controller, 讓gRPC可以與restful api可以工作在同一個專案中.

Grpc.AspNetCore.Server帶來了哪些功能

新增了gRPC middleware之後, asp.net core預設的功能都能夠使用.

DI與Logging

asp.net core中最核心的功能DI可以在gRPC服務中使用.

public class GreeterService : Greeter.GreeterBase
{
    public GreeterService(ILogger<GreeterService> logger)
    {
    }
}
複製程式碼

HttpContext支援

gRPC是基於http/2的, 在ServerCallContext中可以訪問到metadata, 比如說method, host, header等等http的基本資訊. 在Grpc.AspNetCore.Server中對ServerCallContext進行了擴充套件, 可以直接轉換到HttpContext, 這樣就可以訪問session, user ClaimsPrincipal這些基本的資料.

public class GreeterService : Greeter.GreeterBase
{
    public override Task<HelloReply>
        SayHello(HelloRequest request, ServerCallContext context)
    {
        var httpContext = context.GetHttpContext();

        return Task.FromResult(new HelloReply
        {
            Message = "Using https: " + httpContext.Request.IsHttps
        });
    }
}
複製程式碼

相關文章