主要参考文章微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/grpc/client?view=aspnetcore-3.1

此外还参考了文章 https://www.cnblogs.com/stulzq/p/11581967.html并写了一个demo: https://files.cnblogs.com/files/hudean/GrpcDemo.zip 

damo github地址: https://github.com/hudean/GrpcDemo

一、简介

gRPC 是一种与语言无关的高性能远程过程调用 (RPC) 框架。

gRPC 的主要优点是:

  • 现代高性能轻量级 RPC 框架。
  • 协定优先 API 开发,默认使用协议缓冲区,允许与语言无关的实现。
  • 可用于多种语言的工具,以生成强类型服务器和客户端。
  • 支持客户端、服务器和双向流式处理调用。
  • 使用 Protobuf 二进制序列化减少对网络的使用。

这些优点使 gRPC 适用于:

  • 效率至关重要的轻量级微服务。
  • 需要多种语言用于开发的 Polyglot 系统。
  • 需要处理流式处理请求或响应的点对点实时服务。

 

二、创建 gRPC 服务

  • 或者,从 Visual Studio“文件”菜单中选择“新建” > “项目” 。

  • 在“创建新项目”对话框中,选择“gRPC 服务”,然后选择“下一步” :

    ASP.Net Core 3.1 使用gRPC入门指南

  • 将项目命名为“GrpcGreeter”非常重要,这样在复制和粘贴代码时命名空间就会匹配。

  • 选择“创建”。

  • 在“创建新 gRPC 服务”对话框中:

    • 选择“gRPC 服务”模板。
    • 选择“创建”。

运行服务

  • 按 Ctrl+F5 以在不使用调试程序的情况下运行。

    Visual Studio 会显示以下对话框:

    ASP.Net Core 3.1 使用gRPC入门指南

    如果信任 IIS Express SSL 证书,请选择“是” 。

    将显示以下对话框:

    ASP.Net Core 3.1 使用gRPC入门指南

    如果你同意信任开发证书,请选择“是”。

日志显示该服务正在侦听 https://localhost:5001

控制台显示如下:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development

 备注

gRPC 客户端需要使用 HTTPS 调用服务器。


检查项目文件

GrpcGreeter 项目文件:


  • Services 文件夹:包含 Greeter 服务的实现。


上述准备工作完成,开始写gRPC服务端代码!


example.proto文件内容如下

syntax = "proto3";

option csharp_namespace = "GrpcGreeter";

package example;

service exampler {
  // Unarys
  rpc UnaryCall (ExampleRequest) returns (ExampleResponse);

  // Server streaming
  rpc StreamingFromServer (ExampleRequest) returns (stream ExampleResponse);

  // Client streaming
  rpc StreamingFromClient (stream ExampleRequest) returns (ExampleResponse);

  // Bi-directional streaming
  rpc StreamingBothWays (stream ExampleRequest) returns (stream ExampleResponse);
}
message ExampleRequest {
    int32 id = 1;
    string name = 2;
}

message ExampleResponse {
    string msg = 1;
}
example.proto

相关文章:

  • 2019-09-25
  • 2021-10-24
  • 2021-07-16
  • 2021-12-27
  • 2022-02-24
猜你喜欢
  • 2021-10-23
  • 2021-07-03
  • 2021-02-16
  • 2021-01-08
  • 2021-08-11
  • 2021-08-19
相关资源
相似解决方案