热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用gRPC工具生成代码

如何解决《如何使用gRPC工具生成代码》经验,为你挑选了2个好方法。

我已经阅读了本教程,并且能够生成.cs文件,但其中不包含任何服务或rpc定义。

我已经protoc从项目目录中添加到PATH中。

protoc project1.proto --csharp_out="C:\output" --plugin=protoc-gen-grpc="c:\Users\me\.nuget\packages\grpc.tools\1.8.0\tools\windows_x64\grpc_csharp_plugin.exe"

控制台中无错误输出



1> Jon Skeet..:

您需要添加--grpc_out命令行选项,例如add

--grpc_out="C:\output\"

请注意,如果您没有任何服务,它将不会写入任何文件。

这是一个完整的例子。在根目录中,创建:

output目录

tools具有protoc.exe和的目录grpc_csharp_plugin.exe

protos与目录test.proto,如下所示:

test.proto

syntax = "proto3";

service StackOverflowService {
  rpc GetAnswer(Question) returns (Answer);
}

message Question {
  string text = 1;
  string user = 2;
  repeated string tags = 3;
}

message Answer {
  string text = 1;
  string user = 2;
}

然后运行(全部一行;为了便于阅读,我将其破坏了):

tools\protoc.exe -I protos protos\test.proto --csharp_out=output
    --grpc_out=output --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe 

output目录中,你会发现Test.csTestGrpc.cs



2> Doug..:

对于其他发现此问题的人,这里只是一个闲聊的评论,有关此问题的文档非常过时,而且完全是错误的。

安装Grpc.Tools不会在packages文件夹中安装任何内容。那是遗留的行为,即使在Windows上也不再适用。

安装时Grpc.Tools,它将隐藏在本地程序包缓存中,您可以通过调用以下代码来查看:

$ dotnet nuget locals all --list
info : http-cache: /Users/doug/.local/share/NuGet/v3-cache
info : global-packages: /Users/doug/.nuget/packages/
info : temp: /var/folders/xx/s2hnzbrj3yn4hp1bg8q9gb_m0000gn/T/NuGetScratch

所需的二进制文件将位于这些文件夹之一中。

最简单的方法是Grpc.Tools直接从nuget 下载软件包,然后在本地安装。

我已经破解了这个小的帮助程序脚本来执行此操作,该脚本可以在Windows / Mac / Linux上运行,这可以为其他人减轻入门难度:

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Mono.Unix;

namespace BuildProtocol
{
  public class Program
  {
    private const string ToolsUrl = "https://www.nuget.org/api/v2/package/Grpc.Tools/";
    private const string Service = "Greeter";
    private static string ProtocolPath = Path.Combine("..", "protos");
    private static string Protocol = Path.Combine(ProtocolPath, "helloworld.proto");
    private static string Output = Path.Combine("..", "Greeter");

    public static void Main(string[] args)
    {
      RequireTools().Wait();

      var protoc = ProtocPath();
      var plugin = ProtocPluginPath();

      Console.WriteLine($"Using: {protoc}");
      Console.WriteLine($"Using: {plugin}");

      var command = new string[]
      {
        $"-I{ProtocolPath}",
        $"--csharp_out={Output}",
        $"--grpc_out={Output}",
        $"--plugin=protoc-gen-grpc=\"{plugin}\"",
        Protocol,
      };

      Console.WriteLine($"Exec: {protoc} {string.Join(' ', command)}");

      var process = new Process
      {
        StartInfo = new ProcessStartInfo
        {
          UseShellExecute = false,
          FileName = protoc,
          Arguments = string.Join(' ', command)
        }
      };

      process.Start();
      process.WaitForExit();

      Console.WriteLine($"Completed status: {process.ExitCode}");
    }

    public static async Task RequireTools()
    {
      if (!Directory.Exists("Tools"))
      {
        Console.WriteLine("No local tools found, downloading binaries from nuget...");
        Directory.CreateDirectory("Tools");
        await DownloadTools();
        ExtractTools();
      }
    }

    private static void ExtractTools()
    {
      ZipFile.ExtractToDirectory(Path.Combine("Tools", "tools.zip"), Path.Combine("Tools", "bin"));
    }

    private static async Task DownloadTools()
    {
      using (var client = new HttpClient())
      {
        Console.WriteLine($"Fetching: {ToolsUrl}");
        using (var result = await client.GetAsync(ToolsUrl))
        {
          if (!result.IsSuccessStatusCode) throw new Exception($"Unable to download tools ({result.StatusCode}), check URL");
          var localArchive = Path.Combine("Tools", "tools.zip");
          Console.WriteLine($"Saving to: {localArchive}");
          File.WriteAllBytes(localArchive, await result.Content.ReadAsByteArrayAsync());
        }
      }
    }

    private static string ProtocPath()
    {
      var path = Path.Combine("Tools", "bin", "tools", DetermineArch(), "protoc");
      RequireExecutablePermission(path);
      return WithExeExtensionIfRequired(path);
    }

    private static string ProtocPluginPath()
    {
      var path = Path.Combine("Tools", "bin", "tools", DetermineArch(), "grpc_csharp_plugin");
      RequireExecutablePermission(path);
      return WithExeExtensionIfRequired(path);
    }

    private static void RequireExecutablePermission(string path)
    {
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;
      Console.WriteLine($"Ensuring +x on {path}");
      var unixFileInfo = new UnixFileInfo(path);
      unixFileInfo.FileAccessPermissiOns= FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute;
    }

    private static string WithExeExtensionIfRequired(string path)
    {
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
      {
        path += ".exe";
      }

      return path;
    }

    private static string DetermineArch()
    {
      var arch = RuntimeInformation.OSArchitecture;
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
      {
        return WithArch("windows_", arch);
      }

      if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
      {
        return WithArch("macosx_", arch);
      }

      if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
      {
        return WithArch("linux_", arch);
      }

      throw new Exception("Unable to determine runtime");
    }

    private static string WithArch(string platform, Architecture arch)
    {
      switch (arch)
      {
        case Architecture.X64:
          return $"{platform}x86";
        case Architecture.X86:
          return $"{platform}x64";
        default:
          throw new ArgumentOutOfRangeException(nameof(arch), arch, null);
      }
    }
  }
}


@DaisyShipton我不确定该说些什么。如果我的语气不合适,很抱歉,但是教程说明有误,并且不起作用。如果改变了,我会很高兴地更新此答案,但现在就这样。
gRPC C#快速入门确实确实过时了。我创建了https://github.com/grpc/grpc.github.io/pull/728来解决此问题。它包含有关使用dotnet SDK时如何进行代码生成的更新说明。
推荐阅读
  • Postgresql备份和恢复的方法及命令行操作步骤
    本文介绍了使用Postgresql进行备份和恢复的方法及命令行操作步骤。通过使用pg_dump命令进行备份,pg_restore命令进行恢复,并设置-h localhost选项,可以完成数据的备份和恢复操作。此外,本文还提供了参考链接以获取更多详细信息。 ... [详细]
  • 解决VS写C#项目导入MySQL数据源报错“You have a usable connection already”问题的正确方法
    本文介绍了在VS写C#项目导入MySQL数据源时出现报错“You have a usable connection already”的问题,并给出了正确的解决方法。详细描述了问题的出现情况和报错信息,并提供了解决该问题的步骤和注意事项。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • React项目中运用React技巧解决实际问题的总结
    本文总结了在React项目中如何运用React技巧解决一些实际问题,包括取消请求和页面卸载的关联,利用useEffect和AbortController等技术实现请求的取消。文章中的代码是简化后的例子,但思想是相通的。 ... [详细]
  • 本文记录了在vue cli 3.x中移除console的一些采坑经验,通过使用uglifyjs-webpack-plugin插件,在vue.config.js中进行相关配置,包括设置minimizer、UglifyJsPlugin和compress等参数,最终成功移除了console。同时,还包括了一些可能出现的报错情况和解决方法。 ... [详细]
  • 本文详细介绍了git常用命令及其操作方法,包括查看、添加、提交、删除、找回等操作,以及如何重置修改文件、抛弃工作区修改、将工作文件提交到本地暂存区、从版本库中删除文件等。同时还介绍了如何从暂存区恢复到工作文件、恢复最近一次提交过的状态,以及如何合并多个操作等。 ... [详细]
  • 本文介绍了如何使用PHP代码将表格导出为UTF8格式的Excel文件。首先,需要连接到数据库并获取表格的列名。然后,设置文件名和文件指针,并将内容写入文件。最后,设置响应头部,将文件作为附件下载。 ... [详细]
  • 本文介绍了在Ubuntu下制作deb安装包及离线安装包的方法,通过备份/var/cache/apt/archives文件夹中的安装包,并建立包列表及依赖信息文件,添加本地源,更新源列表,可以在没有网络的情况下更新系统。同时提供了命令示例和资源下载链接。 ... [详细]
  • 上图是InnoDB存储引擎的结构。1、缓冲池InnoDB存储引擎是基于磁盘存储的,并将其中的记录按照页的方式进行管理。因此可以看作是基于磁盘的数据库系统。在数据库系统中,由于CPU速度 ... [详细]
  • 本文是一篇翻译文章,介绍了async/await的用法和特点。async关键字被放置在函数前面,意味着该函数总是返回一个promise。文章还提到了可以显式返回一个promise的方法。该特性使得async/await更易于理解和使用。本文还提到了一些可能的错误,并希望读者能够指正。 ... [详细]
  • 本文整理了Java中com.evernote.android.job.JobRequest.getTransientExtras()方法的一些代码示例,展示了 ... [详细]
  • 本文介绍了Hive常用命令及其用途,包括列出数据表、显示表字段信息、进入数据库、执行select操作、导出数据到csv文件等。同时还涉及了在AndroidManifest.xml中获取meta-data的value值的方法。 ... [详细]
  • 目前Miniconda3的主要版本已经不支持python3.6,以Windows为例,在官网Miniconda—Condadocumentation中只有python3.7 ... [详细]
  • 本文整理了Java中org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc.getTypeInfo()方法的一些代码示例,展 ... [详细]
  • oracle恢复失败,RMAN数据库恢复失败解决一例
    问题:这是一个从RAC环境的数据库的RAMN备份恢复到一个单机数据库的操作。当恢复数据文件和恢复正常,但在open数据库时出报下面的错误。--rman备 ... [详细]
author-avatar
海豚的眼泪v
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有