首页 > 其他分享 >Introduction to gRPC

Introduction to gRPC

时间:2024-12-21 23:44:26浏览次数:9  
标签:License Introduction helloworld server gRPC message grpc

Introduction to gRPC

https://grpc.io/docs/what-is-grpc/introduction/

 

An introduction to gRPC and protocol buffers.

This page introduces you to gRPC and protocol buffers. gRPC can use protocol buffers as both its Interface Definition Language (IDL) and as its underlying message interchange format. If you’re new to gRPC and/or protocol buffers, read this! If you just want to dive in and see gRPC in action first, select a language and try its Quick start.

 

Overview

In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.

 

Concept Diagram

 

gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC’s supported languages. So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. In addition, the latest Google APIs will have gRPC versions of their interfaces, letting you easily build Google functionality into your applications.

Working with Protocol Buffers

By default, gRPC uses Protocol Buffers, Google’s mature open source mechanism for serializing structured data (although it can be used with other data formats such as JSON). Here’s a quick intro to how it works. If you’re already familiar with protocol buffers, feel free to skip ahead to the next section.

The first step when working with protocol buffers is to define the structure for the data you want to serialize in a proto file: this is an ordinary text file with a .proto extension. Protocol buffer data is structured as messages, where each message is a small logical record of information containing a series of name-value pairs called fields. Here’s a simple example:

message Person {  string name = 1;  int32 id = 2;  bool has_ponycopter = 3;}// The greeter 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;}

While protocol buffers have been available to open source users for some time, most examples from this site use protocol buffers version 3 (proto3), which has a slightly simplified syntax, some useful new features, and supports more languages. Proto3 is currently available in Java, C++, Dart, Python, Objective-C, C#, a lite-runtime (Android Java), Ruby, and JavaScript from the protocol buffers GitHub repo, as well as a Go language generator from the golang/protobuf official package, with more languages in development. You can find out more in the proto3 language guide and the reference documentation available for each language. The reference documentation also includes a formal specification for the .proto file format.

In general, while you can use proto2 (the current default protocol buffers version), we recommend that you use proto3 with gRPC as it lets you use the full range of gRPC-supported languages, as well as avoiding compatibility issues with proto2 clients talking to proto3 servers and vice versa.

 

demo

https://grpc.io/docs/languages/python/quickstart/

IDL

// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}

  rpc SayHelloStreamReply (HelloRequest) returns (stream HelloReply) {}

  rpc SayHelloBidiStream (stream HelloRequest) returns (stream 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;
}

 

SERVER

# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Python implementation of the GRPC helloworld.Greeter server."""

from concurrent import futures
import logging

import grpc
import helloworld_pb2
import helloworld_pb2_grpc


class Greeter(helloworld_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)


def serve():
    port = "50051"
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port("[::]:" + port)
    server.start()
    print("Server started, listening on " + port)
    server.wait_for_termination()


if __name__ == "__main__":
    logging.basicConfig()
    serve()

 

CLIENT

# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Python implementation of the GRPC helloworld.Greeter client."""

from __future__ import print_function

import logging

import grpc
import helloworld_pb2
import helloworld_pb2_grpc


def run():
    # NOTE(gRPC Python Team): .close() is possible on a channel and should be
    # used in circumstances in which the with statement does not fit the needs
    # of the code.
    print("Will try to greet world ...")
    with grpc.insecure_channel("localhost:50051") as channel:
        stub = helloworld_pb2_grpc.GreeterStub(channel)
        response = stub.SayHello(helloworld_pb2.HelloRequest(name="you"))
    print("Greeter client received: " + response.message)


if __name__ == "__main__":
    logging.basicConfig()
    run()

 

标签:License,Introduction,helloworld,server,gRPC,message,grpc
From: https://www.cnblogs.com/lightsong/p/18621544

相关文章

  • grpc安装(windows or Linux)
    grpc安装(windowsorLinux)下载源码这里使用gRPC最新版本源代码进行编译和安装,版本号为v1.50.0,以下为安装步骤:一、使用Git克隆gRPC到本地在终端中打开某一文件夹,建议新建一个单独存放gRPC源代码的文件夹,输入:gitclone-bv1.50.0https://github.com/grpc/grpc二、安......
  • MATH2033 Introduction to Scientific Computation
    MATH2033IntroductiontoScientificComputation—Coursework2—Submissiondeadline:15:00Friday20December2024Thiscourseworkcontributes10%towardsyourmarkforthismodule.RulesItisnotpermittedtousegenerativeartificialintelligence(AI)......
  • rust可以和C语言程序使用grpc进行通信吗? rust是客户端,C是服务端。 如果可以的话,举一个
    是的,Rust可以与C语言程序通过gRPC进行通信。gRPC是一个语言中立的通信框架,支持多种语言之间的互操作,包括Rust和C。关键步骤概述:定义gRPC接口(.proto文件):定义服务端和客户端之间的接口。C服务端实现:使用C语言实现服务端,处理客户端的请求。Rust客户端实现:使......
  • RPC 服务与 gRPC 的入门案例
    RPC协议RPC(RemoteProcedureCallProtocol)即远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务的协议,允许一个计算机程序可以像调用本地服务一样调用远程服务。RPC的主要作用是不同的服务间方法调用就像本地调用一样便捷,它隐藏了网络通信的细节,使得开发者可......
  • SciTech-Logic:逻辑学-Introduction to Logic: Irvine - 5.5 传统对当方阵
    SciTech-Logic:逻辑学-IntroductiontoLogic:Irvine-5.5传统对当方阵5.5传统对当方阵到目前为止,对直言命题的分析使我们能够进一步研究这些直言命题之间的关系,这也转而为我们日常生活中的许多推理提供了可靠的基础。我们需要另一个技术术语即对当。具有相同主项和相同谓......
  • SciTech-Logic:逻辑学-Introduction to Logic: Irvine - 5.4 质、量 与 周延性
    SciTech-Logic:逻辑学-IntroductiontoLogic:Irvine-5.2ClassandStatement类与直言命题A.质我们已经看到,每个标准直言命题或是肯定或是否定了某类关系。如果一个命题肯定了类与类之间的包含关系,不管是全部地还是部分地肯定,那么,它的质就是肯定的。因此,A命题(“所有S是P......
  • SciTech-Logic:逻辑学-Introduction to Logic: Irvine - 5.2 Class and Statement 类
    类与直言命题亚里士多德三段论逻辑,主要探讨的是关于不同对象类之间相互关系的论证。Class:类Class类,指的是共有certainspecificproperty:某种特定属性的objects:所有对象的collection:汇集。第3章在解释词项内涵的定义时,已经简单地介绍过"class:类"这个概念。Relationso......
  • Introduction to the Explicit Finite Element Method for Nonlinear Transient Dynam
    第一部分基础知识20第1章引言201.1模拟时代与计算机辅助工程201.1.1模拟的世界201.1.2显式有限元方法的发展211.1.3计算机辅助工程CAE——机遇和挑战221.2预备知识231.2.1符号231.2.2弹性本构关系25第2章非线性瞬态动力学显式有限......
  • Introduction to Systems Programming .
    IntroductiontoSystemsProgramming................................................................Assignment2Accompanyingthisassignmentyouwillfindanarchivefilegt2048.zip.Thezip......
  • CS-UY 4563 - Introduction to Machine Learning
    FinalProjectCS-UY4563-IntroductiontoMachineLearningOverviewPartnerwithonestudentandselectamachinelearningproblemofyourchoice.Applythemachinelearningtechniquesyou’velearnedduringthecoursetoyourchosenproblem.Present......