在 ASP.NET Core 中建立 gRPC 客戶端和伺服器

shiningrise發表於2024-11-24

前言

gRPC 是一種高效能、開源的遠端過程呼叫(RPC)框架,它基於 Protocol Buffers(protobuf)定義服務,並使用 HTTP/2 協議進行通訊。

新建專案

新建解決方案GrpcDemo

新建webapi專案GrpcServer作為grpc服務端專案

新增包

    <PackageReference Include="Grpc.AspNetCore" Version="2.67.0" />
    <PackageReference Include="Grpc.Tools" Version="2.67.0">

新建文字檔案greeter.proto

syntax = "proto3";

option csharp_namespace = "GrpcServer";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

編輯GrpcServer專案檔案,新增

新建類GreeterService.cs

using Grpc.Core;

namespace GrpcServer
{
    public class GreeterService : Greeter.GreeterBase
    {
        private readonly ILogger<GreeterService> _logger;
        public GreeterService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
    }
}

修改Program.cs


using GrpcServer;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddGrpc();

var app = builder.Build();

app.MapGrpcService<GreeterService>();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

就是新增下面兩行程式碼

builder.Services.AddGrpc();

app.MapGrpcService<GreeterService>();

新建grpc客戶端專案GrpcClient

新增包

    <PackageReference Include="Google.Protobuf" Version="3.28.3" />
    <PackageReference Include="Grpc.Net.Client" Version="2.67.0" />
    <PackageReference Include="Grpc.Tools" Version="2.67.0">

複製伺服器端端的greeter.proto到客戶端專案

編輯GrpcClient專案檔案,加

編輯Program.cs檔案

using Grpc.Net.Client;
using GrpcClient;

using var channel = GrpcChannel.ForAddress("https://localhost:7052");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(
                  new HelloRequest { Name = "wxy" });
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();

7052改成你的伺服器端執行埠

結果展示

執行伺服器端

執行客戶端

作者

吳曉陽(手機:13736969112微信同號)

相關文章