ASP.NET Web Api 中 Grpc 的简单使用

服务端

添加Nuget包

dotnet add package Grpc.AspNetCore

编写Protobuf文件

syntax = "proto3";

option csharp_namespace = "GrpcGreeter";

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;
}

引入Protobuf文件

<Protobuf Include="greet.proto" GrpcServices="Server" />

重写Greeter的SayHello方法

using Grpc.Core;
using GrpcGreeter;

//Greeter.GreeterBase由greet.proto自动生成
public class GreeterService : Greeter.GreeterBase
{
    private readonly ILogger<GreeterService> _logger;
    public GreeterService(ILogger<GreeterService> logger)
    {
        _logger = logger;
    }

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

Program注册

//注册Grpc
builder.Services.AddGrpc();

//注册GreeterService
app.MapGrpcService<GreeterService>();

设置项目为Https

app.UseHttpsRedirection();

占位 https://www.cnblogs.com/Ar4te-blog/p/18076260

客户端

添加Nuget包

dotnet add package Google.Protobuf
dotnet add package Grpc.Net.Client
dotnet add package Grpc.Tools

复制服务端的Protobuf文件并引入

<Protobuf Include="greet.proto" GrpcServices="Client" />

调用测试

[HttpGet]
public async Task<string> TestGrpc()
{
    // https://localhost:52841 为服务端地址
    using var channel = GrpcChannel.ForAddress("https://localhost:52841");
    var client = new Greeter.GreeterClient(channel);
    var reply = await client.SayHelloAsync(new HelloRequest
                                           {
                                               Name = "GreeterClient
                                           });
    return await Task.FromResult(reply.Message);
}
posted @ 2024-03-18 20:29  Ar4te  阅读(43)  评论(0编辑  收藏  举报