首页 > 其他分享 >netcore grpc

netcore grpc

时间:2024-10-19 16:58:43浏览次数:1  
标签:google proto grpc Apricot netcore garner Grpc import

netcore grpc

一、solution

  1. 创建空解决方案
     > dotnet new sln -n Apricot.Grpc
    

二、Grpc.Server

  1. 创建Apricot.Grpc类库项目
     > dotnet new classlib -n Apricot.Grpc
    
     # 解决方案添加类库项目
     > dotnet sln add Apricot.Grpc/Apricot.Grpc.csproj
    
  2. 安装依赖
     > dotnet add package Grpc.AspNetCore --version 2.66.0
     > dotnet add package protobuf-net --version 3.2.30
    
  3. 创建Protos文件夹
    • 添加Garner文件夹,包含增、删、改、查 等操作
    • 添加 garner.proto 文件 [主文件]
      syntax = "proto3";
      option csharp_namespace = "Apricot.Grpc";
      
      package garner;
      
      // google protos
      import "google/protobuf/empty.proto";
      import "google/protobuf/Any.proto";
      
      // garner protos
      import "Protos/Garner/create.proto";
      import "Protos/Garner/update.proto";
      import "Protos/Garner/get.proto";
      import "Protos/Garner/list.proto";
      
      // params protos
      import "Protos/Params/id.proto";
      import "Protos/Params/query.proto";
      
      // results protos
      import "Protos/Results/result.proto";
      
      // services
      service Garner{
          rpc CreateAsync(CreateGarnerRequest) returns(RcpResult);
      
          rpc UpdateAsync(UpdateGarnerRequest) returns(RcpResult);
      
          rpc RemoveAsync(IdParam) returns(RcpResult);
      
          rpc GetAsync(IdParam) returns(GetGarnerResponse);
      
          rpc GetListAsync(QueryParam) returns(GetGarnerListResponse);
      }
      
      
    • 添加 create.proto 文件
      syntax = "proto3";
      
      option csharp_namespace = "Apricot.Grpc";
      
      package garner;
      
      // google empty.proto
      import "google/protobuf/empty.proto";
      
      // create request
      message CreateGarnerRequest{
          string name = 2;
      
          string address = 3;
      }
      
    • 添加 update.proto 文件
      syntax = "proto3";
      
      option csharp_namespace = "Apricot.Grpc";
      
      package garner;
      
      // google empty.proto
      import "google/protobuf/empty.proto";
      
      // update request
      message UpdateGarnerRequest{
          int64 id = 1;
      
          string name = 2;
      
          string address = 3;
      
      }
      
    • 添加 get.proto 文件
      syntax = "proto3";
      
      option csharp_namespace = "Apricot.Grpc";
      
      
      package garner;
      
      // google empty.proto
      import "google/protobuf/empty.proto";
      
      // garner response
      message GetGarnerResponse{
          int32 code = 1;
          string message = 2;
          bool success = 3;
          oneof garner{
              GetGarnerData data =4;
          }
      }
      
      // garner data
      message GetGarnerData{
          int64 id = 1;
      
          string name = 2;
      
          string address = 3;
      
      }
      
      
    • 添加 list.proto 文件
      syntax = "proto3";
      
      option csharp_namespace = "Apricot.Grpc";
      
      package garner;
      
      // google empty.proto
      import "google/protobuf/empty.proto";
      
      // garner list response
      message GetGarnerListResponse{
          int32 code = 1;
          string message = 2;
          bool success = 3;
          int32 total = 4;
          repeated GetGarnerListData rows = 5;
      }
      
      // garner list data
      message GetGarnerListData{
          int64 id = 1;
      
          string name = 2;
      
          string address = 3;
      
      }
      
  4. 项目文件添加 .proto 配置
    <ItemGroup>
      <Protobuf Include="Protos\Results\result.proto" />
      <Protobuf Include="Protos\Params\query.proto" />
      <Protobuf Include="Protos\Params\id.proto" />
      <Protobuf Include="Protos\Garner\get.proto" />
      <Protobuf Include="Protos\Garner\list.proto" />
      <Protobuf Include="Protos\Garner\update.proto" />
      <Protobuf Include="Protos\Garner\create.proto" />
      <Protobuf Include="Protos\Garner\garner.proto" GrpcServices="Server" />
     </ItemGroup>
    
  5. 编译项目
     > dotnet build
    
  6. 查看生成类
     > dir obj\Debug\net8.0\Protos
    
  7. 创建 grpc service
    • 创建 GarnerGrpcService
    • 继承 Garner.GarnerBase
    • 重写方法
    • 整体代码
       public class GarnerGrpcService : Garner.GarnerBase
       {
         public override Task<RcpResult> CreateAsync(CreateGarnerRequest request, ServerCallContext context)
         {
             return Task.FromResult(new RcpResult
             {
                 Code = StatusCodes.Status200OK,
                 Success = true,
             });
         }
      
         public override Task<RcpResult> UpdateAsync(UpdateGarnerRequest request, ServerCallContext context)
         {
             return Task.FromResult(new RcpResult
             {
                 Code = StatusCodes.Status200OK,
                 Success = true,
             });
         }
      
         public override Task<RcpResult> RemoveAsync(IdParam request, ServerCallContext context)
         {
             return Task.FromResult(new RcpResult
             {
                 Code = StatusCodes.Status200OK,
                 Success = true,
             });
         }
      
         public override Task<GetGarnerResponse> GetAsync(IdParam request, ServerCallContext context)
         {
             return Task.FromResult(new GetGarnerResponse
             {
                 Code = StatusCodes.Status200OK,
                 Success = true,
                 Data = new GetGarnerData
                 {
                     Id = Random.Shared.NextInt64(),
                     Address = "127.0.0.1",
                     Name = "garner"
                 }
             });
         }
      
         public override Task<GetGarnerListResponse> GetListAsync(QueryParam request, ServerCallContext context)
         {
             var response = new GetGarnerListResponse
             {
                 Code = StatusCodes.Status200OK,
                 Success = true,
                 Total = 10,
             };
      
             response.Rows.AddRange(new[]
             {
                 new GetGarnerListData
                 {
                     Id = Random.Shared.NextInt64(),
                     Address = "127.0.0.1",
                     Name = "garner"
                 },
                 new GetGarnerListData
                 {
                     Id = Random.Shared.NextInt64(),
                     Address = "127.0.0.1",
                     Name = "apricot"
                 }
             });
      
             return Task.FromResult(response);
         }
      }
      

三、Grpc.WebApi

  1. 创建Apricot.Grpc.WebApi启动项目
     > dotnet new web -n Apricot.Grpc.WebApi
    
     # 解决方案添加启动项目
     > dotnet sln add Apricot.Grpc.WebApi/Apricot.Grpc.WebApi.csproj
    
  2. 添加项目引用
     > dotnet add reference ../Apricot.Grpc/Apricot.Grpc.csproj
    
  3. 注入容器、管道
     // add grpc
     builder.Services.AddGrpc();
    
     // map grpc
     app.MapGrpcService<GarnerGrpcService>();
    
  4. 协议配置
    {
     "Logging": {
         "LogLevel": {
         "Default": "Information",
         "Microsoft.AspNetCore": "Warning"
         }
     },
     "AllowedHosts": "*",
    
     // setting  http2 protocol
     "Kestrel": {
         "EndpointDefaults": {
          "Protocols": "Http2"
         }
     }
    }
    
    • 支持 Http1/Http2 方法
    builder.WebHost.ConfigureKestrel(options =>
     {
         // http2
         options.ListenAnyIP(5132, listenOption =>
         {
             listenOption.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
         });
    
         // http1
         options.ListenAnyIP(5133, listenOption =>
         {
             listenOption.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1;
         });
     });
    
  5. 启动项目

四、apifox 联调 grpc

  1. 个人团队
  2. 新建项目
    • 类型 grpc 项目
  3. 添加 .proto
    • .proto 文件

      • 选择 garner.proto 主文件
    • 依赖关系目录

      • 选择 Protos 文件夹
    • 错误 & 处理

      • 未找到 google protobuf

      • google protobuf 拷贝 Protos 目录

        • 目录:%USERPROFILE%.nuget\packages\grpc.tools\2.66.0\build\native\include\google
      • 未找到 create.proto

      • garner.protoimport 去掉 Protos/ (仅限导入)

    • 导入成功

  4. 接口测试 create、list
    • create
    • list

标签:google,proto,grpc,Apricot,netcore,garner,Grpc,import
From: https://www.cnblogs.com/study10000/p/18476165

相关文章

  • IoT平台软件:Google Cloud IoT二次开发_RESTfulAPI与gRPC
    RESTfulAPI与gRPCRESTfulAPI原理RESTfulAPI是一种基于HTTP协议的架构风格,用于构建分布式系统中的网络应用程序。它通过一组规则和约束来定义客户端和服务器之间的交互方式,使得系统更加简洁、可扩展和易于理解。RESTfulAPI的设计原则包括:无状态性:每个请求都必......
  • .netcore console 日志和配置
    前言做开发一般会写一些console程序进行调试或者小范围的处理,这里记录下console加日志和配置的过程日志日志这里选择serilog,serilog提供sink,控制台这里我们安装sink.Console和Sinke.File。一共三个nuget包SerilogSerilog.Sinks.ConsoleSerilog.Sinks.File然后代码中配......
  • 【转】netcore 下的 C# 表达式求值
    转自:https://www.cnblogs.com/surfsky/p/12918566.html需求场景:表达式为系统功能维护,提取后,将可执行的表达式放入NetCore下if(表达式)来判定是否正确,因维护的表达式为字符串类型,例如"2>1"需要实现if(2>1){//表达式正确逻辑}else{//表达式不成立逻辑} netframewo......
  • NETCORE - 日志插件 Microsoft.Extensions.Logging
    NETCORE-日志插件Microsoft.Extensions.Loggingnetcore的默认日志插件为 Microsoft.Extensions.Logging,已集成在框架中。使用样例:namespaceRailGraph.Controllers{[ApiController][Route("[controller]")]publicclassANeo4jController:ControllerBas......
  • NetCore 阿里云表格存储插入数据实例
    十年河东,十年河西,莫欺少年穷学无止境,精益求精帮助类:publicclassOtsHelper{publicstaticstringEndpoint="https://xxx.cn-shanghai.ots.aliyuncs.com";publicstaticstringInstanceName="xxx";///<summary>//......
  • crit: Microsoft.AspNetCore.Server.Kestrel[0] Unable to start Kestrel. Interop+Cr
    域名证书没有放在指定的位置错误信息crit:Microsoft.AspNetCore.Server.Kestrel[0]UnabletostartKestrel.Interop+Crypto+OpenSslCryptographicException:error:2006D080:BIOroutines:BIO_new_file:nosuchfileatInterop.Crypto.CheckValidOpenSslHandle(Saf......
  • 【gRPC】2—gRPC与PB&桩代码生成与扩展
    gRPC与PB&桩代码生成与扩展⭐⭐⭐⭐⭐⭐Github主页......
  • .NetCore中下载文件接口指定文件名时中文被替换为下划线(_)的问题
      首先,我这里使用的.net6  比如我有这样一个接口:publicasyncTask<IActionResult>Download(stringname){//省略业务代码...returnFile(stream,"application/octet-stream",name);}  这里下载的文件名时接口参数传进来的,......
  • NetCore 使用 SimpleTCP 实现双工通信
    十年河东,十年河西,莫欺少你穷学无止境,精益求精1、新建netcore控制台应用程序并引入包 2、服务端usingSimpleTCP;usingSystem;usingSystem.Net;usingSystem.Text;namespaceTcpServe{classProgram{staticvoidMain(string[]args)......
  • grpc教程
    1.安装proto下载地址:https://github.com/protocolbuffers/protobuf/releases2.安装依赖gogetgoogle.golang.org/grpc3.安装grpc核心库goinstallgoogle.golang.org/protobuf/cmd/[email protected]/grpc/cmd/protoc-gen-go-grpc@latest......