当前位置:   article > 正文

Envoy代理GRPC服务支持通过restful进行访问_envoy grpc

envoy grpc

一、什么是GRPC

      1.概述

        GRPC是由Google开发的一款语言中立、平台中立、开源的远程过程调用( RPC)技术,主要用来解决性能损失的问题。gRPC使客户端和服务端应用程序可以透明地进行通信,并简化了连接系统的构建。它使用HTTP/2作为通信协议,使用ProtocolBuffers作为序列化协议。

      1.1.Rest和GRPC的对比

            1.1.1优势

        (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更具有优势。

转载:Http系列(二) Http2中的多路复用 - 掘金

     

           1.1.2劣势

            (1)几乎所有的浏览器都支持REST,而支持gRPC的浏览器非常有限。这是REST相对于gRPC的主要优势。 (grpc-web客户端)

            GRPC尚未提供连接池,需要自行实现(envoy解决)

            尚未提供“服务发现”、“负载均衡”机制(istio+envoy解决)

      1.2.应用场景

        适用于低延迟,高吞吐的场景。

        grpc服务可以实时推送消息到客户端,无需前端轮训。

        使用protobuff,独立于语言协议,实现跨语言RPC通讯。

        grpc服务受益于h2和pb协议,传输数据量小

二、GRPC服务端示例(java语言实现)

       2.1服务端

         hello.proto

  1. // proto3版本协议
  2. syntax = "proto3";
  3. //生成的描述信息在一个java文件中
  4. option java_multiple_files = false;
  5. // 生成的包
  6. option java_package = "com.smartsteps.hello.proto";
  7. //该文件声明了入参与回参的相关信息,不需要改动。
  8. option java_outer_classname = "HelloProto";
  9. import "google/api/annotations.proto";
  10. //项目
  11. package hello;
  12. //生成名字+Grpc 该文件声明了接口的信息
  13. service HelloService {
  14. rpc Hello(HelloReq) returns (HelloRsp){
  15. option (google.api.http) = {
  16. get: "/hello"
  17. };
  18. }//
  19. }
  20. message HelloReq{
  21. string name = 1;
  22. string msg = 2;
  23. }
  24. message HelloRsp{
  25. int32 reply = 1;
  26. }

 google的三个文件

annotations.proto

  1. // Copyright 2015 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. syntax = "proto3";
  15. package google.api;
  16. import "google/api/http.proto";
  17. import "google/protobuf/descriptor.proto";
  18. option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
  19. option java_multiple_files = true;
  20. option java_outer_classname = "AnnotationsProto";
  21. option java_package = "com.google.api";
  22. option objc_class_prefix = "GAPI";
  23. extend google.protobuf.MethodOptions {
  24. // See `HttpRule`.
  25. HttpRule http = 72295728;
  26. }

http.proto

  1. // Copyright 2015 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. syntax = "proto3";
  15. package google.api;
  16. option cc_enable_arenas = true;
  17. option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
  18. option java_multiple_files = true;
  19. option java_outer_classname = "HttpProto";
  20. option java_package = "com.google.api";
  21. option objc_class_prefix = "GAPI";
  22. // Defines the HTTP configuration for an API service. It contains a list of
  23. // [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
  24. // to one or more HTTP REST API methods.
  25. message Http {
  26. // A list of HTTP configuration rules that apply to individual API methods.
  27. //
  28. // **NOTE:** All service configuration rules follow "last one wins" order.
  29. repeated HttpRule rules = 1;
  30. // When set to true, URL path parameters will be fully URI-decoded except in
  31. // cases of single segment matches in reserved expansion, where "%2F" will be
  32. // left encoded.
  33. //
  34. // The default behavior is to not decode RFC 6570 reserved characters in multi
  35. // segment matches.
  36. bool fully_decode_reserved_expansion = 2;
  37. }
  38. // # gRPC Transcoding
  39. //
  40. // gRPC Transcoding is a feature for mapping between a gRPC method and one or
  41. // more HTTP REST endpoints. It allows developers to build a single API service
  42. // that supports both gRPC APIs and REST APIs. Many systems, including [Google
  43. // APIs](https://github.com/googleapis/googleapis),
  44. // [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC
  45. // Gateway](https://github.com/grpc-ecosystem/grpc-gateway),
  46. // and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature
  47. // and use it for large scale production services.
  48. //
  49. // `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies
  50. // how different portions of the gRPC request message are mapped to the URL
  51. // path, URL query parameters, and HTTP request body. It also controls how the
  52. // gRPC response message is mapped to the HTTP response body. `HttpRule` is
  53. // typically specified as an `google.api.http` annotation on the gRPC method.
  54. //
  55. // Each mapping specifies a URL path template and an HTTP method. The path
  56. // template may refer to one or more fields in the gRPC request message, as long
  57. // as each field is a non-repeated field with a primitive (non-message) type.
  58. // The path template controls how fields of the request message are mapped to
  59. // the URL path.
  60. //
  61. // Example:
  62. //
  63. // service Messaging {
  64. // rpc GetMessage(GetMessageRequest) returns (Message) {
  65. // option (google.api.http) = {
  66. // get: "/v1/{name=messages/*}"
  67. // };
  68. // }
  69. // }
  70. // message GetMessageRequest {
  71. // string name = 1; // Mapped to URL path.
  72. // }
  73. // message Message {
  74. // string text = 1; // The resource content.
  75. // }
  76. //
  77. // This enables an HTTP REST to gRPC mapping as below:
  78. //
  79. // HTTP | gRPC
  80. // -----|-----
  81. // `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")`
  82. //
  83. // Any fields in the request message which are not bound by the path template
  84. // automatically become HTTP query parameters if there is no HTTP request body.
  85. // For example:
  86. //
  87. // service Messaging {
  88. // rpc GetMessage(GetMessageRequest) returns (Message) {
  89. // option (google.api.http) = {
  90. // get:"/v1/messages/{message_id}"
  91. // };
  92. // }
  93. // }
  94. // message GetMessageRequest {
  95. // message SubMessage {
  96. // string subfield = 1;
  97. // }
  98. // string message_id = 1; // Mapped to URL path.
  99. // int64 revision = 2; // Mapped to URL query parameter `revision`.
  100. // SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`.
  101. // }
  102. //
  103. // This enables a HTTP JSON to RPC mapping as below:
  104. //
  105. // HTTP | gRPC
  106. // -----|-----
  107. // `GET /v1/messages/123456?revision=2&sub.subfield=foo` |
  108. // `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield:
  109. // "foo"))`
  110. //
  111. // Note that fields which are mapped to URL query parameters must have a
  112. // primitive type or a repeated primitive type or a non-repeated message type.
  113. // In the case of a repeated type, the parameter can be repeated in the URL
  114. // as `...?param=A&param=B`. In the case of a message type, each field of the
  115. // message is mapped to a separate parameter, such as
  116. // `...?foo.a=A&foo.b=B&foo.c=C`.
  117. //
  118. // For HTTP methods that allow a request body, the `body` field
  119. // specifies the mapping. Consider a REST update method on the
  120. // message resource collection:
  121. //
  122. // service Messaging {
  123. // rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
  124. // option (google.api.http) = {
  125. // patch: "/v1/messages/{message_id}"
  126. // body: "message"
  127. // };
  128. // }
  129. // }
  130. // message UpdateMessageRequest {
  131. // string message_id = 1; // mapped to the URL
  132. // Message message = 2; // mapped to the body
  133. // }
  134. //
  135. // The following HTTP JSON to RPC mapping is enabled, where the
  136. // representation of the JSON in the request body is determined by
  137. // protos JSON encoding:
  138. //
  139. // HTTP | gRPC
  140. // -----|-----
  141. // `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id:
  142. // "123456" message { text: "Hi!" })`
  143. //
  144. // The special name `*` can be used in the body mapping to define that
  145. // every field not bound by the path template should be mapped to the
  146. // request body. This enables the following alternative definition of
  147. // the update method:
  148. //
  149. // service Messaging {
  150. // rpc UpdateMessage(Message) returns (Message) {
  151. // option (google.api.http) = {
  152. // patch: "/v1/messages/{message_id}"
  153. // body: "*"
  154. // };
  155. // }
  156. // }
  157. // message Message {
  158. // string message_id = 1;
  159. // string text = 2;
  160. // }
  161. //
  162. //
  163. // The following HTTP JSON to RPC mapping is enabled:
  164. //
  165. // HTTP | gRPC
  166. // -----|-----
  167. // `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id:
  168. // "123456" text: "Hi!")`
  169. //
  170. // Note that when using `*` in the body mapping, it is not possible to
  171. // have HTTP parameters, as all fields not bound by the path end in
  172. // the body. This makes this option more rarely used in practice when
  173. // defining REST APIs. The common usage of `*` is in custom methods
  174. // which don't use the URL at all for transferring data.
  175. //
  176. // It is possible to define multiple HTTP methods for one RPC by using
  177. // the `additional_bindings` option. Example:
  178. //
  179. // service Messaging {
  180. // rpc GetMessage(GetMessageRequest) returns (Message) {
  181. // option (google.api.http) = {
  182. // get: "/v1/messages/{message_id}"
  183. // additional_bindings {
  184. // get: "/v1/users/{user_id}/messages/{message_id}"
  185. // }
  186. // };
  187. // }
  188. // }
  189. // message GetMessageRequest {
  190. // string message_id = 1;
  191. // string user_id = 2;
  192. // }
  193. //
  194. // This enables the following two alternative HTTP JSON to RPC mappings:
  195. //
  196. // HTTP | gRPC
  197. // -----|-----
  198. // `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
  199. // `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id:
  200. // "123456")`
  201. //
  202. // ## Rules for HTTP mapping
  203. //
  204. // 1. Leaf request fields (recursive expansion nested messages in the request
  205. // message) are classified into three categories:
  206. // - Fields referred by the path template. They are passed via the URL path.
  207. // - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They are passed via the HTTP
  208. // request body.
  209. // - All other fields are passed via the URL query parameters, and the
  210. // parameter name is the field path in the request message. A repeated
  211. // field can be represented as multiple query parameters under the same
  212. // name.
  213. // 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL query parameter, all fields
  214. // are passed via URL path and HTTP request body.
  215. // 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP request body, all
  216. // fields are passed via URL path and URL query parameters.
  217. //
  218. // ### Path template syntax
  219. //
  220. // Template = "/" Segments [ Verb ] ;
  221. // Segments = Segment { "/" Segment } ;
  222. // Segment = "*" | "**" | LITERAL | Variable ;
  223. // Variable = "{" FieldPath [ "=" Segments ] "}" ;
  224. // FieldPath = IDENT { "." IDENT } ;
  225. // Verb = ":" LITERAL ;
  226. //
  227. // The syntax `*` matches a single URL path segment. The syntax `**` matches
  228. // zero or more URL path segments, which must be the last part of the URL path
  229. // except the `Verb`.
  230. //
  231. // The syntax `Variable` matches part of the URL path as specified by its
  232. // template. A variable template must not contain other variables. If a variable
  233. // matches a single path segment, its template may be omitted, e.g. `{var}`
  234. // is equivalent to `{var=*}`.
  235. //
  236. // The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL`
  237. // contains any reserved character, such characters should be percent-encoded
  238. // before the matching.
  239. //
  240. // If a variable contains exactly one path segment, such as `"{var}"` or
  241. // `"{var=*}"`, when such a variable is expanded into a URL path on the client
  242. // side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The
  243. // server side does the reverse decoding. Such variables show up in the
  244. // [Discovery
  245. // Document](https://developers.google.com/discovery/v1/reference/apis) as
  246. // `{var}`.
  247. //
  248. // If a variable contains multiple path segments, such as `"{var=foo/*}"`
  249. // or `"{var=**}"`, when such a variable is expanded into a URL path on the
  250. // client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded.
  251. // The server side does the reverse decoding, except "%2F" and "%2f" are left
  252. // unchanged. Such variables show up in the
  253. // [Discovery
  254. // Document](https://developers.google.com/discovery/v1/reference/apis) as
  255. // `{+var}`.
  256. //
  257. // ## Using gRPC API Service Configuration
  258. //
  259. // gRPC API Service Configuration (service config) is a configuration language
  260. // for configuring a gRPC service to become a user-facing product. The
  261. // service config is simply the YAML representation of the `google.api.Service`
  262. // proto message.
  263. //
  264. // As an alternative to annotating your proto file, you can configure gRPC
  265. // transcoding in your service config YAML files. You do this by specifying a
  266. // `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same
  267. // effect as the proto annotation. This can be particularly useful if you
  268. // have a proto that is reused in multiple services. Note that any transcoding
  269. // specified in the service config will override any matching transcoding
  270. // configuration in the proto.
  271. //
  272. // Example:
  273. //
  274. // http:
  275. // rules:
  276. // # Selects a gRPC method and applies HttpRule to it.
  277. // - selector: example.v1.Messaging.GetMessage
  278. // get: /v1/messages/{message_id}/{sub.subfield}
  279. //
  280. // ## Special notes
  281. //
  282. // When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the
  283. // proto to JSON conversion must follow the [proto3
  284. // specification](https://developers.google.com/protocol-buffers/docs/proto3#json).
  285. //
  286. // While the single segment variable follows the semantics of
  287. // [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String
  288. // Expansion, the multi segment variable **does not** follow RFC 6570 Section
  289. // 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion
  290. // does not expand special characters like `?` and `#`, which would lead
  291. // to invalid URLs. As the result, gRPC Transcoding uses a custom encoding
  292. // for multi segment variables.
  293. //
  294. // The path variables **must not** refer to any repeated or mapped field,
  295. // because client libraries are not capable of handling such variable expansion.
  296. //
  297. // The path variables **must not** capture the leading "/" character. The reason
  298. // is that the most common use case "{var}" does not capture the leading "/"
  299. // character. For consistency, all path variables must share the same behavior.
  300. //
  301. // Repeated message fields must not be mapped to URL query parameters, because
  302. // no client library can support such complicated mapping.
  303. //
  304. // If an API needs to use a JSON array for request or response body, it can map
  305. // the request or response body to a repeated field. However, some gRPC
  306. // Transcoding implementations may not support this feature.
  307. message HttpRule {
  308. // Selects a method to which this rule applies.
  309. //
  310. // Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
  311. string selector = 1;
  312. // Determines the URL pattern is matched by this rules. This pattern can be
  313. // used with any of the {get|put|post|delete|patch} methods. A custom method
  314. // can be defined using the 'custom' field.
  315. oneof pattern {
  316. // Maps to HTTP GET. Used for listing and getting information about
  317. // resources.
  318. string get = 2;
  319. // Maps to HTTP PUT. Used for replacing a resource.
  320. string put = 3;
  321. // Maps to HTTP POST. Used for creating a resource or performing an action.
  322. string post = 4;
  323. // Maps to HTTP DELETE. Used for deleting a resource.
  324. string delete = 5;
  325. // Maps to HTTP PATCH. Used for updating a resource.
  326. string patch = 6;
  327. // The custom pattern is used for specifying an HTTP method that is not
  328. // included in the `pattern` field, such as HEAD, or "*" to leave the
  329. // HTTP method unspecified for this rule. The wild-card rule is useful
  330. // for services that provide content to Web (HTML) clients.
  331. CustomHttpPattern custom = 8;
  332. }
  333. // The name of the request field whose value is mapped to the HTTP request
  334. // body, or `*` for mapping all request fields not captured by the path
  335. // pattern to the HTTP body, or omitted for not having any HTTP request body.
  336. //
  337. // NOTE: the referred field must be present at the top-level of the request
  338. // message type.
  339. string body = 7;
  340. // Optional. The name of the response field whose value is mapped to the HTTP
  341. // response body. When omitted, the entire response message will be used
  342. // as the HTTP response body.
  343. //
  344. // NOTE: The referred field must be present at the top-level of the response
  345. // message type.
  346. string response_body = 12;
  347. // Additional HTTP bindings for the selector. Nested bindings must
  348. // not contain an `additional_bindings` field themselves (that is,
  349. // the nesting may only be one level deep).
  350. repeated HttpRule additional_bindings = 11;
  351. }
  352. // A custom pattern is used for defining custom HTTP verb.
  353. message CustomHttpPattern {
  354. // The name of this custom HTTP verb.
  355. string kind = 1;
  356. // The path matched by this custom verb.
  357. string path = 2;
  358. }

status.proto

  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. syntax = "proto3";
  15. package google.rpc;
  16. import "google/protobuf/any.proto";
  17. option cc_enable_arenas = true;
  18. option go_package = "google.golang.org/genproto/googleapis/rpc/status;status";
  19. option java_multiple_files = true;
  20. option java_outer_classname = "StatusProto";
  21. option java_package = "com.google.rpc";
  22. option objc_class_prefix = "RPC";
  23. // The `Status` type defines a logical error model that is suitable for
  24. // different programming environments, including REST APIs and RPC APIs. It is
  25. // used by [gRPC](https://github.com/grpc). Each `Status` message contains
  26. // three pieces of data: error code, error message, and error details.
  27. //
  28. // You can find out more about this error model and how to work with it in the
  29. // [API Design Guide](https://cloud.google.com/apis/design/errors).
  30. message Status {
  31. // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].
  32. int32 code = 1;
  33. // A developer-facing error message, which should be in English. Any
  34. // user-facing error message should be localized and sent in the
  35. // [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.
  36. string message = 2;
  37. // A list of messages that carry the error details. There is a common set of
  38. // message types for APIs to use.
  39. repeated google.protobuf.Any details = 3;
  40. }

编译proto文件的 java pom

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <maven.compiler.source>1.8</maven.compiler.source>
  4. <maven.compiler.target>1.8</maven.compiler.target>
  5. <java.version>1.8</java.version>
  6. <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
  7. <protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
  8. <grpc-stater-version>2.11.0.RELEASE</grpc-stater-version>
  9. </properties>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.1.6.RELEASE</version>
  14. <relativePath/>
  15. </parent>
  16. <dependencies>
  17. <dependency>
  18. <groupId>net.devh</groupId>
  19. <artifactId>grpc-spring-boot-starter</artifactId>
  20. <version>${grpc-stater-version}</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>com.google.protobuf</groupId>
  24. <artifactId>protobuf-java-util</artifactId>
  25. <version>3.12.0</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.projectlombok</groupId>
  29. <artifactId>lombok</artifactId>
  30. <version>1.18.8</version>
  31. </dependency>
  32. </dependencies>
  33. <build>
  34. <extensions>
  35. <extension>
  36. <groupId>kr.motd.maven</groupId>
  37. <artifactId>os-maven-plugin</artifactId><!--引入操作系统os设置的属性插件,否则${os.detected.classifier} 操作系统版本会找不到 -->
  38. <version>1.5.0.Final</version>
  39. </extension>
  40. </extensions>
  41. <finalName>${project.artifactId}</finalName>
  42. <plugins>
  43. <plugin>
  44. <groupId>org.xolstice.maven.plugins</groupId>
  45. <artifactId>protobuf-maven-plugin</artifactId>
  46. <version>${protobuf-maven-plugin.version}</version>
  47. <configuration>
  48. <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
  49. <pluginId>grpc-java</pluginId>
  50. <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier}</pluginArtifact>
  51. <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
  52. <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
  53. <clearOutputDirectory>false</clearOutputDirectory>
  54. </configuration>
  55. <executions>
  56. <execution>
  57. <goals>
  58. <goal>compile</goal>
  59. <goal>compile-custom</goal>
  60. </goals>
  61. </execution>
  62. </executions>
  63. </plugin>
  64. <plugin>
  65. <groupId>org.apache.maven.plugins</groupId>
  66. <artifactId>maven-compiler-plugin</artifactId>
  67. <executions>
  68. <execution>
  69. <phase>compile</phase>
  70. <goals>
  71. <goal>compile</goal>
  72. </goals>
  73. </execution>
  74. </executions>
  75. </plugin>
  76. <plugin>
  77. <groupId>org.springframework.boot</groupId>
  78. <artifactId>spring-boot-maven-plugin</artifactId>
  79. <executions>
  80. <execution>
  81. <goals>
  82. <goal>repackage</goal>
  83. </goals>
  84. <configuration>
  85. <mainClass>com.smartsteps.hello.HelloApplication</mainClass>
  86. </configuration>
  87. </execution>
  88. </executions>
  89. </plugin>
  90. </plugins>
  91. </build>

在目录下执行mvn  clean compile即可生成相关的java文件。

HelloGrpcService代码:
  1. @GrpcService
  2. @Slf4j
  3. public class HelloGrpcService extends HelloServiceGrpc.HelloServiceImplBase {
  4. @Override
  5. public void hello(HelloProto.HelloReq request, StreamObserver<HelloProto.HelloRsp> responseObserver) {
  6. String name = request.getName();
  7. String msg = request.getMsg();
  8. log.info("收到客户端发来的消息.name->{},msg->{}", name, msg);
  9. HelloProto.HelloRsp helloRsp = HelloProto.HelloRsp.newBuilder().setReply(1).build();
  10. responseObserver.onNext(helloRsp);
  11. responseObserver.onCompleted();
  12. }
  13. }

yml配置文件

  1. grpc:
  2. server:
  3. port: 8080
  4. enable-keep-alive: true #是否使用keepalive
  5. keep-alive-time: 30s #client发送keepalive的间隔
  6. keep-alive-timeout: 10s # keepalive 超时时间
  7. permit-keep-alive-without-calls: true # 没有数据包也可发送ping,保活状态

此时程序可以作为一个GRPC服务运行起来,可以供其他GRPC客户端调用。

三、Envoy代理GRPC服务端

  3.1.什么是Envoy

  1. envoy 是作为微服务服务架构中以独立进程方式实现高级网络功能的,轻量级的7层服务代理程序,通常以sidecar的方式运行在应用程序的周边,也可以作为网络的边缘代理来运行
  2. envoy 的特性 进程外体系结构 ,L3/L4过滤器体系结构,HTTP L7过滤器体系结构, 一流的HTTP/2支持, HTTP/3支持(目前为alpha),HTTP L7路由,gRPC支持,服务发现和动态配置,健康检查,高级负载平衡,前端/边缘代理支持, 一流的可观察性

  3.2.Envoy组件拓扑

     

   3.3. Envoy代理服务端支持restful访问

   直接上配置文件:

  1. static_resources:
  2. listeners:
  3. - name: listener_0
  4. address:
  5. socket_address: { address: 0.0.0.0, port_value: 10000 }
  6. filter_chains:
  7. - filters:
  8. - name: envoy.filters.network.http_connection_manager
  9. typed_config:
  10. "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
  11. codec_type: auto
  12. stat_prefix: ingress_http
  13. route_config:
  14. name: local_route
  15. virtual_hosts:
  16. - name: local_service
  17. domains: ["*"]
  18. routes:
  19. - match: { prefix: "/" }
  20. route:
  21. #timeout: 0s
  22. cluster: hello_service
  23. max_stream_duration:
  24. grpc_timeout_header_max: 0s
  25. cors:
  26. allow_origin_string_match:
  27. - prefix: "*"
  28. allow_credentials: true
  29. allow_methods: GET, PUT, DELETE, POST, OPTIONS
  30. 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
  31. max_age: "17280000"
  32. expose_headers: custom-header-1,grpc-status,grpc-message
  33. http_filters:
  34. - name: envoy.filters.http.grpc_web
  35. - name: envoy.filters.http.grpc_json_transcoder
  36. typed_config:
  37. "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder
  38. proto_descriptor: "/etc/envoy/hello.pb"
  39. services: ["hello.HelloService"]
  40. print_options:
  41. add_whitespace: true
  42. always_print_primitive_fields: true
  43. always_print_enums_as_ints: false
  44. preserve_proto_field_names: false
  45. - name: envoy.filters.http.cors
  46. - name: envoy.filters.http.router
  47. clusters:
  48. - name: hello_service
  49. connect_timeout: 0.25s
  50. type: logical_dns
  51. http2_protocol_options: {}
  52. lb_policy: round_robin
  53. load_assignment:
  54. cluster_name: cluster_0
  55. endpoints:
  56. - lb_endpoints:
  57. - endpoint:
  58. address:
  59. socket_address:
  60. address: app
  61. port_value: 8080

我使用10000端口代理后端GRPC服务的8080端口。

pb文件需要自己生成,我选择用python生成,需要自己安装python环境和googleapi-master,google的依赖包我已经给出

googleapi-master: github.com/googleapis/googleapis

命令:

  1. python -m grpc_tools.protoc -I ../../../../googleapis-master -I. --include_imports --include_source_info --descrip
  2. tor_set_out=hello.pb --python_out=.. --grpc_python_out=.. hello.proto

envoy的Dockerfile

  1. FROM envoyproxy/envoy:v1.18-latest
  2. #FROM envoyproxy/envoy-alpine:v1.18-latest
  3. COPY envoy.yaml /etc/envoy/envoy.yaml
  4. COPY hello.pb /etc/envoy/hello.pb

Docker-compose:

  1. version: '3'
  2. services:
  3. envoy:
  4. build:
  5. context: ./envoy
  6. dockerfile: Dockerfile
  7. image: smartp/envoy
  8. depends_on:
  9. - app
  10. - power
  11. ports:
  12. - "10000:10000"
  13. networks:
  14. - eproxy
  15. app:
  16. build:
  17. context: ./app
  18. dockerfile: Dockerfile
  19. image: smartp/dbapp
  20. networks:
  21. - eproxy
  22. networks:
  23. eproxy:
  24. driver: bridge

访问测试: 

http://localhost:10000/hello?name=hello&msg=word

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/181659
推荐阅读
  

闽ICP备14008679号