赞
踩
GRPC是由Google开发的一款语言中立、平台中立、开源的远程过程调用( RPC)技术,主要用来解决性能损失的问题。gRPC使客户端和服务端应用程序可以透明地进行通信,并简化了连接系统的构建。它使用HTTP/2作为通信协议,使用ProtocolBuffers作为序列化协议。
(1)拥有现代高性能轻量级RPC框架。
(2)约定优先的API开发,默认使用Protocol Buffers 作为描述语言,允许与语言无关的实现。
(3)可用于多种语言的工具,以生成强类型的服务器和客户端。
(4)支持客户端和服务器双向流调用。
(5)通过Protocol Buffers 二进制序列化减少网络使用。(6)Rest只支持一元(客户端发出单个请求并接收单个响应)传输,GRPC支持一元,服务端流,客户端流,双向流。
(7)REST遵循基于HTTP 1.1的请求-响应通信模型,而gRPC遵循基于HTTP 2.0的客户端-响应通信模型。HTTP 2.0在速度上有着绝对的优势
Http发展路程
从 Http/0.9 到 Http/2 要发送多个请求,从多个 Tcp 连接=>keep-alive=>管道化=>多路复用不断的减少多次创建 Tcp 等等带来的性能损耗。
多个 Tcp 连接
在最早的时候没有
keep-alive
只能创建多个Tcp
连接来做多次请求。多次 http 请求效果如下图所示:一次请求完成就会关闭本次的 Tcp 连接,下个请求又要从新建立 Tcp 连接传输完成数据再关闭,造成很大的性能损耗。
Keep-Alive
Keep-Alive
解决的核心问题是: 一定时间内,同一域名多次请求数据,只建立一次 HTTP 请求,其他请求可复用每一次建立的连接通道,以达到提高请求效率的问题。这里面所说的一定时间是可以配置的,不管你用的是Apache
还是nginx
。 以往,浏览器判断响应数据是否接收完毕,是看连接是否关闭。在使用Keep-Alive后,就不能这样了,这就要求服务器对持久连接的响应头部一定要返回content-length
标识body的
长度,供浏览器判断界限。有时,content-length
的方法并不是太准确,也可以使用Transfer-Encoding: chunked
头部发送一串一串的数据,最后由长度为 0 的chunked
标识结束。 多次 http 请求效果如下图所示:上图:设置 Connection:Keep-Alive,保持连接在一段时间内不断开。
Keep-Alive
还是存在如下问题:
- 串行的文件传输。
- 同域并行请求限制带来的阻塞(6~8)个
管线化
HTTP 管线化可以克服同域并行请求限制带来的阻塞,它是建立在持久连接之上,是把所有请求一并发给服务器,但是服务器需要按照顺序一个一个响应,而不是等到一个响应回来才能发下一个请求,这样就节省了很多请求到服务器的时间。不过,HTTP 管线化仍旧有阻塞的问题,若上一响应迟迟不回,后面的响应都会被阻塞到。
上图:HTTPpipelining:建立多个连接
多路复用
多路复用代替原来的序列和阻塞机制。所有就是请求的都是通过一个 TCP 连接并发完成。因为在多路复用之前所有的传输是基于基础文本的,在多路复用中是基于二进制数据帧的传输、消息、流,所以可以做到乱序的传输。多路复用对同一域名下所有请求都是基于流,所以不存在同域并行的阻塞。多次请求如下图:
上图:多路复用
REST使用JSON或XML编码格式承载数据,而gRPC默认使用ProtoBuf编码格式承载数据。JSON或XML编码格式以文本形式传输,而ProtoBuf是以二进制数据进行传输,所以在传输速率上gRPC更具有优势。
(1)几乎所有的浏览器都支持REST,而支持gRPC的浏览器非常有限。这是REST相对于gRPC的主要优势。 (grpc-web客户端)
GRPC尚未提供连接池,需要自行实现(envoy解决)
尚未提供“服务发现”、“负载均衡”机制(istio+envoy解决)
适用于低延迟,高吞吐的场景。
grpc服务可以实时推送消息到客户端,无需前端轮训。
使用protobuff,独立于语言协议,实现跨语言RPC通讯。
grpc服务受益于h2和pb协议,传输数据量小
hello.proto
// proto3版本协议 syntax = "proto3"; //生成的描述信息在一个java文件中 option java_multiple_files = false; // 生成的包 option java_package = "com.smartsteps.hello.proto"; //该文件声明了入参与回参的相关信息,不需要改动。 option java_outer_classname = "HelloProto"; import "google/api/annotations.proto"; //项目 package hello; //生成名字+Grpc 该文件声明了接口的信息 service HelloService { rpc Hello(HelloReq) returns (HelloRsp){ option (google.api.http) = { get: "/hello" }; }// } message HelloReq{ string name = 1; string msg = 2; } message HelloRsp{ int32 reply = 1; }
google的三个文件
annotations.proto
// Copyright 2015 Google LLC // // 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"; package google.api; import "google/api/http.proto"; import "google/protobuf/descriptor.proto"; option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; option java_multiple_files = true; option java_outer_classname = "AnnotationsProto"; option java_package = "com.google.api"; option objc_class_prefix = "GAPI"; extend google.protobuf.MethodOptions { // See `HttpRule`. HttpRule http = 72295728; }
http.proto
// Copyright 2015 Google LLC // // 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"; package google.api; option cc_enable_arenas = true; option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; option java_multiple_files = true; option java_outer_classname = "HttpProto"; option java_package = "com.google.api"; option objc_class_prefix = "GAPI"; // Defines the HTTP configuration for an API service. It contains a list of // [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method // to one or more HTTP REST API methods. message Http { // A list of HTTP configuration rules that apply to individual API methods. // // **NOTE:** All service configuration rules follow "last one wins" order. repeated HttpRule rules = 1; // When set to true, URL path parameters will be fully URI-decoded except in // cases of single segment matches in reserved expansion, where "%2F" will be // left encoded. // // The default behavior is to not decode RFC 6570 reserved characters in multi // segment matches. bool fully_decode_reserved_expansion = 2; } // # gRPC Transcoding // // gRPC Transcoding is a feature for mapping between a gRPC method and one or // more HTTP REST endpoints. It allows developers to build a single API service // that supports both gRPC APIs and REST APIs. Many systems, including [Google // APIs](https://github.com/googleapis/googleapis), // [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC // Gateway](https://github.com/grpc-ecosystem/grpc-gateway), // and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature // and use it for large scale production services. // // `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies // how different portions of the gRPC request message are mapped to the URL // path, URL query parameters, and HTTP request body. It also controls how the // gRPC response message is mapped to the HTTP response body. `HttpRule` is // typically specified as an `google.api.http` annotation on the gRPC method. // // Each mapping specifies a URL path template and an HTTP method. The path // template may refer to one or more fields in the gRPC request message, as long // as each field is a non-repeated field with a primitive (non-message) type. // The path template controls how fields of the request message are mapped to // the URL path. // // Example: // // service Messaging { // rpc GetMessage(GetMessageRequest) returns (Message) { // option (google.api.http) = { // get: "/v1/{name=messages/*}" // }; // } // } // message GetMessageRequest { // string name = 1; // Mapped to URL path. // } // message Message { // string text = 1; // The resource content. // } // // This enables an HTTP REST to gRPC mapping as below: // // HTTP | gRPC // -----|----- // `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")` // // Any fields in the request message which are not bound by the path template // automatically become HTTP query parameters if there is no HTTP request body. // For example: // // service Messaging { // rpc GetMessage(GetMessageRequest) returns (Message) { // option (google.api.http) = { // get:"/v1/messages/{message_id}" // }; // } // } // message GetMessageRequest { // message SubMessage { // string subfield = 1; // } // string message_id = 1; // Mapped to URL path. // int64 revision = 2; // Mapped to URL query parameter `revision`. // SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. // } // // This enables a HTTP JSON to RPC mapping as below: // // HTTP | gRPC // -----|----- // `GET /v1/messages/123456?revision=2&sub.subfield=foo` | // `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: // "foo"))` // // Note that fields which are mapped to URL query parameters must have a // primitive type or a repeated primitive type or a non-repeated message type. // In the case of a repeated type, the parameter can be repeated in the URL // as `...?param=A¶m=B`. In the case of a message type, each field of the // message is mapped to a separate parameter, such as // `...?foo.a=A&foo.b=B&foo.c=C`. // // For HTTP methods that allow a request body, the `body` field // specifies the mapping. Consider a REST update method on the // message resource collection: // // service Messaging { // rpc UpdateMessage(UpdateMessageRequest) returns (Message) { // option (google.api.http) = { // patch: "/v1/messages/{message_id}" // body: "message" // }; // } // } // message UpdateMessageRequest { // string message_id = 1; // mapped to the URL // Message message = 2; // mapped to the body // } // // The following HTTP JSON to RPC mapping is enabled, where the // representation of the JSON in the request body is determined by // protos JSON encoding: // // HTTP | gRPC // -----|----- // `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: // "123456" message { text: "Hi!" })` // // The special name `*` can be used in the body mapping to define that // every field not bound by the path template should be mapped to the // request body. This enables the following alternative definition of // the update method: // // service Messaging { // rpc UpdateMessage(Message) returns (Message) { // option (google.api.http) = { // patch: "/v1/messages/{message_id}" // body: "*" // }; // } // } // message Message { // string message_id = 1; // string text = 2; // } // // // The following HTTP JSON to RPC mapping is enabled: // // HTTP | gRPC // -----|----- // `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: // "123456" text: "Hi!")` // // Note that when using `*` in the body mapping, it is not possible to // have HTTP parameters, as all fields not bound by the path end in // the body. This makes this option more rarely used in practice when // defining REST APIs. The common usage of `*` is in custom methods // which don't use the URL at all for transferring data. // // It is possible to define multiple HTTP methods for one RPC by using // the `additional_bindings` option. Example: // // service Messaging { // rpc GetMessage(GetMessageRequest) returns (Message) { // option (google.api.http) = { // get: "/v1/messages/{message_id}" // additional_bindings { // get: "/v1/users/{user_id}/messages/{message_id}" // } // }; // } // } // message GetMessageRequest { // string message_id = 1; // string user_id = 2; // } // // This enables the following two alternative HTTP JSON to RPC mappings: // // HTTP | gRPC // -----|----- // `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` // `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: // "123456")` // // ## Rules for HTTP mapping // // 1. Leaf request fields (recursive expansion nested messages in the request // message) are classified into three categories: // - Fields referred by the path template. They are passed via the URL path. // - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They are passed via the HTTP // request body. // - All other fields are passed via the URL query parameters, and the // parameter name is the field path in the request message. A repeated // field can be represented as multiple query parameters under the same // name. // 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL query parameter, all fields // are passed via URL path and HTTP request body. // 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP request body, all // fields are passed via URL path and URL query parameters. // // ### Path template syntax // // Template = "/" Segments [ Verb ] ; // Segments = Segment { "/" Segment } ; // Segment = "*" | "**" | LITERAL | Variable ; // Variable = "{" FieldPath [ "=" Segments ] "}" ; // FieldPath = IDENT { "." IDENT } ; // Verb = ":" LITERAL ; // // The syntax `*` matches a single URL path segment. The syntax `**` matches // zero or more URL path segments, which must be the last part of the URL path // except the `Verb`. // // The syntax `Variable` matches part of the URL path as specified by its // template. A variable template must not contain other variables. If a variable // matches a single path segment, its template may be omitted, e.g. `{var}` // is equivalent to `{var=*}`. // // The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` // contains any reserved character, such characters should be percent-encoded // before the matching. // // If a variable contains exactly one path segment, such as `"{var}"` or // `"{var=*}"`, when such a variable is expanded into a URL path on the client // side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The // server side does the reverse decoding. Such variables show up in the // [Discovery // Document](https://developers.google.com/discovery/v1/reference/apis) as // `{var}`. // // If a variable contains multiple path segments, such as `"{var=foo/*}"` // or `"{var=**}"`, when such a variable is expanded into a URL path on the // client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. // The server side does the reverse decoding, except "%2F" and "%2f" are left // unchanged. Such variables show up in the // [Discovery // Document](https://developers.google.com/discovery/v1/reference/apis) as // `{+var}`. // // ## Using gRPC API Service Configuration // // gRPC API Service Configuration (service config) is a configuration language // for configuring a gRPC service to become a user-facing product. The // service config is simply the YAML representation of the `google.api.Service` // proto message. // // As an alternative to annotating your proto file, you can configure gRPC // transcoding in your service config YAML files. You do this by specifying a // `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same // effect as the proto annotation. This can be particularly useful if you // have a proto that is reused in multiple services. Note that any transcoding // specified in the service config will override any matching transcoding // configuration in the proto. // // Example: // // http: // rules: // # Selects a gRPC method and applies HttpRule to it. // - selector: example.v1.Messaging.GetMessage // get: /v1/messages/{message_id}/{sub.subfield} // // ## Special notes // // When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the // proto to JSON conversion must follow the [proto3 // specification](https://developers.google.com/protocol-buffers/docs/proto3#json). // // While the single segment variable follows the semantics of // [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String // Expansion, the multi segment variable **does not** follow RFC 6570 Section // 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion // does not expand special characters like `?` and `#`, which would lead // to invalid URLs. As the result, gRPC Transcoding uses a custom encoding // for multi segment variables. // // The path variables **must not** refer to any repeated or mapped field, // because client libraries are not capable of handling such variable expansion. // // The path variables **must not** capture the leading "/" character. The reason // is that the most common use case "{var}" does not capture the leading "/" // character. For consistency, all path variables must share the same behavior. // // Repeated message fields must not be mapped to URL query parameters, because // no client library can support such complicated mapping. // // If an API needs to use a JSON array for request or response body, it can map // the request or response body to a repeated field. However, some gRPC // Transcoding implementations may not support this feature. message HttpRule { // Selects a method to which this rule applies. // // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. string selector = 1; // Determines the URL pattern is matched by this rules. This pattern can be // used with any of the {get|put|post|delete|patch} methods. A custom method // can be defined using the 'custom' field. oneof pattern { // Maps to HTTP GET. Used for listing and getting information about // resources. string get = 2; // Maps to HTTP PUT. Used for replacing a resource. string put = 3; // Maps to HTTP POST. Used for creating a resource or performing an action. string post = 4; // Maps to HTTP DELETE. Used for deleting a resource. string delete = 5; // Maps to HTTP PATCH. Used for updating a resource. string patch = 6; // The custom pattern is used for specifying an HTTP method that is not // included in the `pattern` field, such as HEAD, or "*" to leave the // HTTP method unspecified for this rule. The wild-card rule is useful // for services that provide content to Web (HTML) clients. CustomHttpPattern custom = 8; } // The name of the request field whose value is mapped to the HTTP request // body, or `*` for mapping all request fields not captured by the path // pattern to the HTTP body, or omitted for not having any HTTP request body. // // NOTE: the referred field must be present at the top-level of the request // message type. string body = 7; // Optional. The name of the response field whose value is mapped to the HTTP // response body. When omitted, the entire response message will be used // as the HTTP response body. // // NOTE: The referred field must be present at the top-level of the response // message type. string response_body = 12; // Additional HTTP bindings for the selector. Nested bindings must // not contain an `additional_bindings` field themselves (that is, // the nesting may only be one level deep). repeated HttpRule additional_bindings = 11; } // A custom pattern is used for defining custom HTTP verb. message CustomHttpPattern { // The name of this custom HTTP verb. string kind = 1; // The path matched by this custom verb. string path = 2; }
status.proto
// Copyright 2020 Google LLC // // 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"; package google.rpc; import "google/protobuf/any.proto"; option cc_enable_arenas = true; option go_package = "google.golang.org/genproto/googleapis/rpc/status;status"; option java_multiple_files = true; option java_outer_classname = "StatusProto"; option java_package = "com.google.rpc"; option objc_class_prefix = "RPC"; // The `Status` type defines a logical error model that is suitable for // different programming environments, including REST APIs and RPC APIs. It is // used by [gRPC](https://github.com/grpc). Each `Status` message contains // three pieces of data: error code, error message, and error details. // // You can find out more about this error model and how to work with it in the // [API Design Guide](https://cloud.google.com/apis/design/errors). message Status { // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. int32 code = 1; // A developer-facing error message, which should be in English. Any // user-facing error message should be localized and sent in the // [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. string message = 2; // A list of messages that carry the error details. There is a common set of // message types for APIs to use. repeated google.protobuf.Any details = 3; }
编译proto文件的 java pom
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <maven.compiler.source>1.8</maven.compiler.source>
- <maven.compiler.target>1.8</maven.compiler.target>
- <java.version>1.8</java.version>
- <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
- <protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
- <grpc-stater-version>2.11.0.RELEASE</grpc-stater-version>
- </properties>
-
-
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.6.RELEASE</version>
- <relativePath/>
- </parent>
-
-
-
- <dependencies>
- <dependency>
- <groupId>net.devh</groupId>
- <artifactId>grpc-spring-boot-starter</artifactId>
- <version>${grpc-stater-version}</version>
- </dependency>
- <dependency>
- <groupId>com.google.protobuf</groupId>
- <artifactId>protobuf-java-util</artifactId>
- <version>3.12.0</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.18.8</version>
- </dependency>
-
- </dependencies>
-
-
- <build>
-
- <extensions>
- <extension>
- <groupId>kr.motd.maven</groupId>
- <artifactId>os-maven-plugin</artifactId><!--引入操作系统os设置的属性插件,否则${os.detected.classifier} 操作系统版本会找不到 -->
- <version>1.5.0.Final</version>
- </extension>
- </extensions>
-
- <finalName>${project.artifactId}</finalName>
- <plugins>
- <plugin>
- <groupId>org.xolstice.maven.plugins</groupId>
- <artifactId>protobuf-maven-plugin</artifactId>
- <version>${protobuf-maven-plugin.version}</version>
- <configuration>
- <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
- <pluginId>grpc-java</pluginId>
- <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier}</pluginArtifact>
- <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
- <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
- <clearOutputDirectory>false</clearOutputDirectory>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>compile</goal>
- <goal>compile-custom</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <executions>
- <execution>
- <phase>compile</phase>
- <goals>
- <goal>compile</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>repackage</goal>
- </goals>
- <configuration>
- <mainClass>com.smartsteps.hello.HelloApplication</mainClass>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- </plugins>
-
-
- </build>
在目录下执行mvn clean compile即可生成相关的java文件。
HelloGrpcService代码:
- @GrpcService
- @Slf4j
- public class HelloGrpcService extends HelloServiceGrpc.HelloServiceImplBase {
-
- @Override
- public void hello(HelloProto.HelloReq request, StreamObserver<HelloProto.HelloRsp> responseObserver) {
- String name = request.getName();
- String msg = request.getMsg();
- log.info("收到客户端发来的消息.name->{},msg->{}", name, msg);
- HelloProto.HelloRsp helloRsp = HelloProto.HelloRsp.newBuilder().setReply(1).build();
- responseObserver.onNext(helloRsp);
- responseObserver.onCompleted();
- }
- }
yml配置文件
- grpc:
- server:
- port: 8080
- enable-keep-alive: true #是否使用keepalive
- keep-alive-time: 30s #client发送keepalive的间隔
- keep-alive-timeout: 10s # keepalive 超时时间
- permit-keep-alive-without-calls: true # 没有数据包也可发送ping,保活状态
此时程序可以作为一个GRPC服务运行起来,可以供其他GRPC客户端调用。
直接上配置文件:
- static_resources:
- listeners:
- - name: listener_0
- address:
- socket_address: { address: 0.0.0.0, port_value: 10000 }
- filter_chains:
- - filters:
- - name: envoy.filters.network.http_connection_manager
- typed_config:
- "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
- codec_type: auto
- stat_prefix: ingress_http
- route_config:
- name: local_route
- virtual_hosts:
- - name: local_service
- domains: ["*"]
- routes:
- - match: { prefix: "/" }
- route:
- #timeout: 0s
- cluster: hello_service
- max_stream_duration:
- grpc_timeout_header_max: 0s
- cors:
- allow_origin_string_match:
- - prefix: "*"
- allow_credentials: true
- allow_methods: GET, PUT, DELETE, POST, OPTIONS
- allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,custom-header-1,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout
- max_age: "17280000"
- expose_headers: custom-header-1,grpc-status,grpc-message
- http_filters:
- - name: envoy.filters.http.grpc_web
- - name: envoy.filters.http.grpc_json_transcoder
- typed_config:
- "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder
- proto_descriptor: "/etc/envoy/hello.pb"
- services: ["hello.HelloService"]
- print_options:
- add_whitespace: true
- always_print_primitive_fields: true
- always_print_enums_as_ints: false
- preserve_proto_field_names: false
- - name: envoy.filters.http.cors
- - name: envoy.filters.http.router
- clusters:
- - name: hello_service
- connect_timeout: 0.25s
- type: logical_dns
- http2_protocol_options: {}
- lb_policy: round_robin
- load_assignment:
- cluster_name: cluster_0
- endpoints:
- - lb_endpoints:
- - endpoint:
- address:
- socket_address:
- address: app
- port_value: 8080
我使用10000端口代理后端GRPC服务的8080端口。
pb文件需要自己生成,我选择用python生成,需要自己安装python环境和googleapi-master,google的依赖包我已经给出
googleapi-master: github.com/googleapis/googleapis
命令:
- python -m grpc_tools.protoc -I ../../../../googleapis-master -I. --include_imports --include_source_info --descrip
- tor_set_out=hello.pb --python_out=.. --grpc_python_out=.. hello.proto
envoy的Dockerfile
- FROM envoyproxy/envoy:v1.18-latest
- #FROM envoyproxy/envoy-alpine:v1.18-latest
- COPY envoy.yaml /etc/envoy/envoy.yaml
- COPY hello.pb /etc/envoy/hello.pb
Docker-compose:
- version: '3'
- services:
- envoy:
- build:
- context: ./envoy
- dockerfile: Dockerfile
- image: smartp/envoy
- depends_on:
- - app
- - power
- ports:
- - "10000:10000"
- networks:
- - eproxy
- app:
- build:
- context: ./app
- dockerfile: Dockerfile
- image: smartp/dbapp
- networks:
- - eproxy
-
-
- networks:
- eproxy:
- driver: bridge
-
访问测试:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。