gRPC-web:基础教程

Basics tutorial

基础教程

A basic tutorial introduction to gRPC-web.

gRPC-web的基本教程介绍。

This tutorial provides a basic introduction on how to use gRPC-Web from browsers.

本教程提供了关于如何从浏览器使用gRPC-Web的基本介绍。

By walking through this example you’ll learn how to:

通过浏览此示例,将学会如何:

  • Define a service in a .proto file.
  • 在.proto文件中定义服务。
  • Generate client code using the protocol buffer compiler.
  • 使用协议缓冲区编译器生成客户端代码。
  • Use the gRPC-Web API to write a simple client for your service.
  • 使用gRPC-Web API为服务编写一个简单的客户端。

It assumes a passing familiarity with protocol buffers.

​假定对协议缓冲区有一点熟悉。

Why use gRPC and gRPC-Web?

为什么要使用gRPC和gRPC-Web?

With gRPC you can define your service once in a .proto file and implement clients and servers in any of gRPC’s supported languages, which in turn can be run in environments ranging from servers inside a large data center to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. You also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. gRPC-Web lets you access gRPC services built in this manner from browsers using an idiomatic API.

使用gRPC,可以在.proto文件中定义一次服务,并用gRPC支持的任何语言实现客户端和服务器,这些语言和服务器可以在从大型数据中心内的服务器到自己的平板电脑的各种环境中运行-不同语言和环境之间通信的所有复杂性都由gRPC处理。还可以获得使用协议缓冲区的所有优点,包括高效的序列化、简单的IDL和轻松的接口更新。gRPC-Web允许使用惯用的API从浏览器访问以这种方式构建的gRPC服务。

Define the Service

定义服务

The first step when creating a gRPC service is to define the service methods and their request and response message types using protocol buffers. In this example, we define our EchoService in a file called echo.proto. For more information about protocol buffers and proto3 syntax, please see the protobuf documentation.

​创建gRPC服务的第一步是使用协议缓冲区定义服务方法及其请求和响应消息类型。在这个例子中,我们在一个名为echo.proto的文件中定义了EchoService。有关协议缓冲区和proto3语法的更多信息,请参阅protobuf文档。

message EchoRequest {
  string message = 1;
}

message EchoResponse {
  string message = 1;
}

service EchoService {
  rpc Echo(EchoRequest) returns (EchoResponse);
}

Implement gRPC Backend Server

实现gRPC后端服务器

Next, we implement our EchoService interface using Node in the backend gRPC EchoServer. This will handle requests from clients. See the file node-server/server.js for details.

​接下来,我们使用后端gRPC EchoServer中的Node实现我们的EchoService接口。这将处理来自客户端的请求。有关详细信息,请参阅文件node-server/server.js。

You can implement the server in any language supported by gRPC. Please see the main page for more details.

​可以用gRPC支持的任何语言实现服务器。有关更多详细信息,请参阅主页。

function doEcho(call, callback) {
  callback(null, {message: call.request.message});
}

Configure the Envoy Proxy

配置Envoy代理

In this example, we will use the Envoy proxy to forward the gRPC browser request to the backend server. You can see the complete config file in envoy.yaml

​在本例中,我们将使用Envoy代理将gRPC浏览器请求转发到后端服务器。可以在envoy.yaml中看到完整的配置文件

To forward the gRPC requests to the backend server, we need a block like this:

要将gRPC请求转发到后端服务器,我们需要这样的块:

  listeners:
  - name: listener_0
    address:
      socket_address: { address: 0.0.0.0, port_value: 8080 }
    filter_chains:
    - filters:
      - name: envoy.http_connection_manager
        config:
          codec_type: auto
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_service
              domains: ["*"]
              routes:
              - match: { prefix: "/" }
                route: { cluster: echo_service }
          http_filters:
          - name: envoy.grpc_web
          - name: envoy.router
  clusters:
  - name: echo_service
    connect_timeout: 0.25s
    type: logical_dns
    http2_protocol_options: {}
    lb_policy: round_robin
    hosts: [{ socket_address: { address: node-server, port_value: 9090 }}]

You may also need to add some CORS setup to make sure the browser can request cross-origin content.

可能还需要添加一些CORS设置,以确保浏览器可以请求跨来源内容。

In this simple example, the browser makes gRPC requests to port :8080. Envoy forwards the request to the backend gRPC server listening on port :9090.

在这个简单的示例中,浏览器向端口8080发出gRPC请求。Envoy将请求转发到侦听端口9090的后端gRPC服务器。

Generate Protobuf Messages and Service Client Stub

生成Protobuf消息和服务客户端存根

To generate the protobuf message classes from our echo.proto, run the following command:

要从echo.proto生成protobuf消息类,请运行以下命令:

$ protoc -I=$DIR echo.proto \
  --js_out=import_style=commonjs:$OUT_DIR

The import_style option passed to the --js_out flag makes sure the generated files will have CommonJS style require() statements.

传递给--js_out标志的import_style选项确保生成的文件具有CommonJS样式的require()语句。

To generate the gRPC-Web service client stub, first you need the gRPC-Web protoc plugin. To compile the plugin protoc-gen-grpc-web, you need to run this from the repo’s root directory:

要生成gRPC-Web服务客户端存根,首先需要gRPC-Web协议插件。要编译插件protoc-gen-grpc-web,需要从repo的根目录运行:

$ cd grpc-web
$ sudo make install-plugin

To generate the service client stub file, run this command:

要生成服务客户端存根文件,请运行以下命令:

$ protoc -I=$DIR echo.proto \
  --grpc-web_out=import_style=commonjs,mode=grpcwebtext:$OUT_DIR

In the --grpc-web_out param above:

在上面的--grpc-web_out参数中:

  • mode can be grpcwebtext (default) or grpcweb
  • node可以是grpcwebtext(默认)或grpcweb
  • import_style can be closure (default) or commonjs
  • import_style可以是闭包(默认)或commonjs

Our command generates the client stub, by default, to the file echo_grpc_web_pb.js.

默认情况下,我们的命令会将客户端存根生成到文件echo_grpc_web_pb.js中。

Write JS Client Code

编写JS客户端代码

Now you are ready to write some JS client code. Put this in a client.js file.

现在已经准备好编写一些JS客户端代码了。将其放入client.js文件中。

const {EchoRequest, EchoResponse} = require('./echo_pb.js');
const {EchoServiceClient} = require('./echo_grpc_web_pb.js');

var echoService = new EchoServiceClient('http://localhost:8080');

var request = new EchoRequest();
request.setMessage('Hello World!');

echoService.echo(request, {}, function(err, response) {
  // ...
});

You will need a package.json file

需要一个package.json文件

{
  "name": "grpc-web-commonjs-example",
  "dependencies": {
    "google-protobuf": "^3.6.1",
    "grpc-web": "^0.4.0"
  },
  "devDependencies": {
    "browserify": "^16.2.2",
    "webpack": "^4.16.5",
    "webpack-cli": "^3.1.0"
  }
}

Compile the JS Library

编译JS库

Finally, putting all these together, we can compile all the relevant JS files into one single JS library that can be used in the browser.

最后,将所有这些放在一起,我们可以将所有相关的JS文件编译成一个可以在浏览器中使用的JS库。

$ npm install
$ npx webpack client.js

Now embed dist/main.js into your project and see it in action!

现在将dist/main.js嵌入到项目中,并查看它的实际操作!

Last modified February 16, 2023: Update Protocol Buffers documentation URL (#1092) (852a744)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值