转载请注明来自ChenJiehua《GRPC快速入门》

GRPC是一个高性能、通用的开源RPC框架,基于HTTP/2协议标准和Protobuf序列化协议开发,支持众多的开发语言。

概述

在GRPC框架中,客户端可以像调用本地对象一样直接调用位于不同机器的服务端方法,如此我们就可以非常方便的创建一些分布式的应用服务。

在服务端,我们实现了所定义的服务和可供远程调用的方法,运行一个gRPC server来处理客户端的请求;在客户端,gRPC实现了一个stub(可以简单理解为一个client),其提供跟服务端相同的方法。

gRPC使用protocol buffers作为接口描述语言(IDL)以及底层的信息交换格式,一般情况下推荐使用 proto3因为其能够支持更多的语言,并减少一些兼容性的问题。

简单示例如下:

// 定义了一个服务 Greeter
service Greeter {
// 定义方法 SayHello
rpc SayHello (HelloRequest) returns (HelloReply) {}
} // request
message HelloRequest {
string name = 1;
} // response
message HelloReply {
string message = 1;
}

gRPC使用 protoc 和一个插件来将proto定义的内容生成客户端/服务端的代码。

Proto定义

helloworld.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto"; package helloworld; // The greeting 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;
}

Go示例

安装grpc和protobuf

1、gRPC要求 Go 版本 >= 1.6

2、安装 gRPC:

$ go get -u -v google.golang.org/grpc

3、安装 Protocol Buffers v3:

github下载预编译的protoc,然后安装 protoc-gen-go:

$ go get -v -u github.com/golang/protobuf/protoc-gen-go

生成 gRPC代码

$ protoc -I. --go_out=plugins=grpc:. helloworld.proto

Server 代码

server.go

package main

import (
"log"
"net" "golang.org/x/net/context"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
"google.golang.org/grpc/reflection"
) const (
port = ":50051"
) // server is used to implement helloworld.GreeterServer.
type server struct{} // SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
} func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

Client 代码

client.go

package main

import (
"log"
"os"
"time" "golang.org/x/net/context"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
) const (
address = "localhost:50051"
defaultName = "world"
) func main() {
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn) // Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}

Python示例

安装grpc和protobuf

1、新建个虚拟环境:

$ pip install virtualenv
$ virtualenv venv
$ source venv/bin/activate
$ pip install -U pip

2、在虚拟环境中安装grpc和protobuf:

$ pip install grpcio

3、安装 grpc tools:

python的grpc tools包含了protoc及其插件,用来生成客户端和服务端代码

$ pip install grpcio-tools

4、安装 grpc reflection:

grpc reflection 使得服务端支持 grpc_cli 进行调试

$ pip install grpcio-reflection

生成 gRPC 代码

$ python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto

Server 代码

server.py

"""The Python implementation of the GRPC helloworld.Greeter server."""

from concurrent import futures
import time import grpc
from grpc.reflection.v1alpha import reflection<br>
import helloworld_pb2
import helloworld_pb2_grpc _ONE_DAY_IN_SECONDS = 60 * 60 * 24 class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
reflection.enable_server_reflection([h.service_name() for h in server._state.generic_handlers], server)
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0) if __name__ == '__main__':
serve()

Client 代码

client.py

"""The Python implementation of the GRPC helloworld.Greeter client."""

from __future__ import print_function

import grpc

import helloworld_pb2
import helloworld_pb2_grpc def run():
channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message) if __name__ == '__main__':
run()

grpc_cli命令行工具

为了使用 grpc_cli ,我们需要从源码进行安装。

1、从github获取源码:

 $ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc
$ cd grpc
$ git submodule update --init

2、编译 grpc_cli:

# Linux下需要 gflags
$ sudo apt-get install libgflags-dev
$ make grpc_cli

3、使用 grpc_cli:

# 查看所有的服务
$ grpc_cli ls localhost:50051 # 查看 Greeter 服务的详细信息
$ grpc_cli ls localhost:50051 helloworld.Greeter -l # 查看 Greeter.SayHello 方法的详细信息
$ grpc_cli ls localhost:50051 helloworld.Greeter.SayHello -l # 远程调用
$ grpc_cli call localhost:50051 SayHello "name: 'gRPC CLI'"

参考:

GRPC快速入门的更多相关文章

  1. gRPC快速入门记录

    为什么使用grpc 1.protocl buffer一种高效的序列化结构. 2.支持http 2.0标准化协议. http/2 1.http/2对每个源只需创建一个持久连接,在这一个连接内,可以并行的 ...

  2. Golang Module快速入门

    前言: 在Golang1.11之前的版本中,官方没有提供依赖和包管理工具.开发者通常会使用vendor或者glide的方式来管理依赖(也有直接使用GOPATH多环境方式),而在Golang1.11之后 ...

  3. Web Api 入门实战 (快速入门+工具使用+不依赖IIS)

    平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html 屁话我也就不多说了,什么简介的也省了,直接简单概括+demo ...

  4. SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=》提升)

     SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=>提升,5个Demo贯彻全篇,感兴趣的玩才是真的学) 官方demo:http://www.asp.net/si ...

  5. 前端开发小白必学技能—非关系数据库又像关系数据库的MongoDB快速入门命令(2)

    今天给大家道个歉,没有及时更新MongoDB快速入门的下篇,最近有点小忙,在此向博友们致歉.下面我将简单地说一下mongdb的一些基本命令以及我们日常开发过程中的一些问题.mongodb可以为我们提供 ...

  6. 【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  7. 【番外篇】ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  8. Mybatis框架 的快速入门

    MyBatis 简介 什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果 ...

  9. grunt快速入门

    快速入门 Grunt和 Grunt 插件是通过 npm 安装并管理的,npm是 Node.js 的包管理器. Grunt 0.4.x 必须配合Node.js >= 0.8.0版本使用.:奇数版本 ...

随机推荐

  1. mybatis学习(五)(动态mybatis(多条件查询))

    有时候要查询条件是多条件的,尤其是使用mybatis的时候如何创建sql语句呢? 这里mybatis有自己的办法,如下: 案例:通过传入map,根据map里面的数据来查询 mapper配置如下: &l ...

  2. 【朝花夕拾】Android自定义View篇之(十一)View的滑动,弹性滑动与自定义PagerView

    前言 由于手机屏幕尺寸有限,但是又经常需要在屏幕中显示大量的内容,这就使得必须有部分内容显示,部分内容隐藏.这就需要用一个Android中很重要的概念——滑动.滑动,顾名思义就是view从一个地方移动 ...

  3. [记录] Linux登录前后提示语

    Linux登录前后提示语 /etc/issue 本地(虚拟控制台KVM等)登录前提示语,支持转义字符 /etc/issue.net 远程(telnet,ssh)登录前提示语,不支持转义字符 /etc/ ...

  4. VS2010中GetMenu()和GetSubMenu(0)为NULL引发异常的解决方法 及添加方法

    对于前面问题的分析:来源于http://blog.163.com/yuyang_tech/blog/static/216050083201211144120401/ 解决方法1: //来源:http: ...

  5. pdo类的使用

    使用方法 2.php <?php require_once "./mypdo.php"; $pdo = DAOPDO::getInstance('localhost', 'r ...

  6. Excel催化剂开源第38波-json字符串转多个表格结构

    作为开发者来说,面对json字符一点不陌生,但对于普通用户来说,更合适的是数据表结构的数据,最好数据已经躺在Excel表格内,不用到处导入导出操作.所以开发者和用户之间是有不同的数据使用思维和需求的. ...

  7. VUE v-for循环中每个item节点动态绑定不同函数方法

    一. 业务场景: 一个title 处 可能有 一个或多个按钮,  按钮对应不同的响应事件 二. 思路 : 按钮个数 根据传入的数据length 来循环渲染,  每条数据对应的事件名称 通过动态绑定 三 ...

  8. Error:(949) Multiple substitutions specified in non-positional format; Android格式化string.xml

    string.xml问题代码 <string name="msg">书名:%s\n价格:%d</string> 异常信息 Error:(949) Multi ...

  9. C#3.0新增功能03 隐式类型本地变量

    连载目录    [已更新最新开发文章,点击查看详细] 从 Visual C# 3.0 开始,在方法范围内声明的变量可以具有隐式“类型”var. 隐式类型本地变量为强类型,就像用户已经自行声明该类型,但 ...

  10. C#3.0新增功能10 表达式树 03 支持表达式树的框架类型

    连载目录    [已更新最新开发文章,点击查看详细] 存在可与表达式树配合使用的 .NET Core framework 中的类的大型列表. 可以在 System.Linq.Expressions 查 ...