美文网首页
使用GRPC

使用GRPC

作者: 黑山老雕 | 来源:发表于2020-04-07 18:24 被阅读0次

    C# .NET Framework

    对于C# .NET Framework平台,使用GRPC for C#,GRPC有两种实现,一个是基于grpc C库为核心来实现的,一个是基于纯粹DotNet Core来实现的。如果你用DotNet Framework,mono,那么最好用这个。如果用纯粹的dotnet Core,那么可以用C# with grpc-dotnet

    在build中集成protobuf的方式:https://github.com/grpc/grpc/blob/v1.28.1/src/csharp/BUILD-INTEGRATION.md

    可以参考两个例子,一个叫做helloworldLegacyCsproj,使用传统的Framework项目的组织形式,或者参考 HelloWorld,使用 dotnet core的项目组织形式。

    链接中,提到了需要把grpc.tools库标记为 development-only,在传统方式中,修改 packages.config,在doenet new方式中,增加 PrivateAssets='All' 属性
    我理解这段主要还是对于要发布自己的Nuget包的用户吧。

    对于传统项目,手动添加protobuf文件,并将build action设置为ProtoBuf,这个选项在添加 grpc.tools包后会在下拉列表中出现。


    image.png

    对于SDK项目(dotnet new),在文件属性中可以选择protobuf和其他更多的属性 (感觉这段像废话)

    如果只是想编出来source,而不是直接打到Assembly中,链接提供了另一种方式,不过个人感觉不必看了,基本就是添加 OurtputDir 和 CompileOutputs为False

    如果protobuf文件在别的文件夹,可以添加成为一个链接过来:
    Or, if using Visual Studio, add files as links from outside directory. In the Add Files dialog, there is a little down arrow near the Open button. Click on it, and choose "Add as link". If you do not select this option, Visual Studio will copy files to the project directory instead.

    通常情况下,应该会使用第一种最常用的方法,记得protobuf修改后,编译才能生成新版本的cs哦。(当然你是无感的,但是要理解这个原理,比如在引用代码的时候发现没有自动提示,就先build一下)

    Python

    Python使用grpc相当简单。下载两个库

    pip install grpcio
    pip install grpcio-tools
    

    然后 python -m grpcio-tools.protoc 来编译生成python文件,引用即可。
    pb2后缀的是protobuf带的消息,grpc结尾的是grpc里面定义的service和rpc等类

    Protobuf文档:https://developers.google.com/protocol-buffers/docs/proto3#nested

    GRPC 函数参考:https://grpc.github.io/grpc/python/grpc.html

    Transcoding

    Transcoding 可以让grpc服务同时支持 grpc call 和 RESTFUL接口,但这个功能似乎是需要平台支持的。自己随便定义一下应该是不行的。
    https://cloud.google.com/endpoints/docs/grpc/transcoding
    https://github.com/googleapis/googleapis/blob/master/google/api/http.proto

    ProtoBuff 的一些概念

    option

    option 字段定义一些选项,比如当处理java的时候,类名是什么之类的。option的完整定义列表在:google/protobuf/descriptor.proto

    相关文章

      网友评论

          本文标题:使用GRPC

          本文链接:https://www.haomeiwen.com/subject/xuinphtx.html