Concept of analytical
grpc
GRPC is a modern open source high-performance Remote Procedure Call (RPC) framework that can run in any environment. With pluggable support for load balancing, tracing, health checking, and authentication
More information :www.grpc.io/
grpc-web
Grpc-web provides a Javascript library that allows browser clients to access gRPC services
protobuf
Protobuf is Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data — think XML, but smaller, faster, and simpler. You can define how data is structured once, and then you can easily write and read structured data in various data streams using various languages using specially generated source code.
envoy
Envoy is an L7 proxy and communication bus designed for large modern SOA (Service Oriented Architecture) architectures. Here we mainly use HTTP2.0 proxies
grpc(node server)
- New the helloworld. Proto
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Copy the code
- Node. js writes a GRPC server
var PROTO_PATH = __dirname + "/helloworld.proto";
var assert = require("assert");
var grpc = require("@grpc/grpc-js");
var protoLoader = require("@grpc/proto-loader");
var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true.longs: String.enums: String.defaults: true.oneofs: true});var protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
var helloworld = protoDescriptor.helloworld;
function doSayHello(call, callback) {
callback(null, {
message: "Hello! " + call.request.name,
});
}
function getServer() {
var server = new grpc.Server();
server.addService(helloworld.Greeter.service, {
// Corresponds to the protobuf service method
sayHello: doSayHello,
});
return server;
}
if (require.main === module) {
var server = getServer();
server.bindAsync(
"0.0.0.0:9090",
grpc.ServerCredentials.createInsecure(),
(err, port) = >{ assert.ifError(err); server.start(); }); }exports.getServer = getServer;
Copy the code
- package.json
{
"dependencies": {
"@grpc/grpc-js": "^ 1.3.7." "."@grpc/proto-loader": "^ 0.6.4"."grpc": "^ 1.24.11"."lodash": "^ 4.17.21"}}Copy the code
4. Run debugging To facilitate debugging, you can install a Nodemon hot load
npm install -g nodemon
node server.js
or
nodemon server.js
Copy the code
Envoy agent
Many tutorials do not elaborate on http2.0 proxies, and browsers cannot access interfaces without proxies
- Install Envoy (MAC Installation, other systems own Baidu)
brew install envoy
Copy the code
- New envoy. Yarml
Static_resources: listeners: name: listener_0 address: socket_address: {address: 0.0.0.0, port_value: 8181 } 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: cluster: greeter_service max_stream_duration: grpc_timeout_header_max: 0s cors: allow_origin_string_match: - prefix: "*" 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-enc oding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout max_age: "1728000" expose_headers: custom-header-1,grpc-status,grpc-message http_filters: - name: envoy.filters.http.grpc_web - name: envoy.filters.http.cors - name: envoy.filters.http.router clusters: - name: greeter_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: 0.0.0.0 port_value: 9090Copy the code
Port:
Proxy port:
- Start the broker
envoy -c envoy.yaml
Copy the code
Vue3 GRPC – Web data access
1. Protobuf protoc-gen- GRPC – Web installation (MAC, other systems own Baidu)
brew install protobuf
brew install protoc-gen-grpc-web
Copy the code
2. Protobuf js transformation
protoc helloworld.proto \
--js_out=import_style=commonjs:./ \
--grpc-web_out=import_style=commonjs,mode=grpcwebtext:./
Copy the code
The result is two JS files
- Here we are almost done. Any project vUE or React can be used. Here I use VUe3.
<template>
<div>
<h1>grpc-web</h1>
data :{{ state.data }}
</div>
</template>
<script setup>
import { reactive } from "vue";
const state = reactive({
data: ""});const { HelloRequest } = require("./helloworld_pb.js");
const { GreeterClient } = require("./helloworld_grpc_web_pb.js");
// Remember that the calling interface is not the server interface
var client = new GreeterClient("http://localhost:8181");
var request = new HelloRequest();
request.setName("Jack");
// Interface call
client.sayHello(request, {}, (err, response) = > {
console.log(response.getMessage());
state.data = response.getMessage();
});
// The streaming call server is not implemented
// client.sayHello(request, {}, (err, response) => {
// response.on("data", (data) => {
// console.log(data.getMessage());
// state.data = data.getMessage();
/ /});
// response.on("end", () => {
// console.log("end");
/ /});
// });
</script>
Copy the code
Results show
As shown in the figure, using GRPC Protobuf makes data smaller, saves bandwidth, and transfers data faster than traditional HTTP JSON data communication. It is essential in projects with large amount of data and frequent data interaction. When you are older, record it for the convenience of using 😄 in the future.