1. The premise
Simply put, RPC is a function or method (collectively referred to as a service) on a remote machine that is executed by a caller using a parameter passing method. RPC hides specific communication details throughout the process.
At the heart of RPC is the purpose: to locally invoke remote (cross-memory accessible) methods.
RPC framework: an out-of-the-box framework that implements RPC calls, including open source frameworks such as Ali Dubbo, Google gRPC, and Facebook Thrift
Remote communication protocols: REST(HTTP JSON), SOAP(HTTP XML), gRPC(HTTP2 Protobuf)
Serialization/deserialization: Text (XML, JSON) versus binary (Java native) versus Protobuf
The bold ones are chosen here
2. Prepare Proto files to define unified interfaces
File: hello. Proto
syntax = "proto3"; package api; RPC SayHello (HelloRequest) returns (HelloResponse) {} Message HelloRequest {// String name = 1; } // we can write the response structure comment message HelloResponse { }Copy the code
3. Prepare Python environment
pip install grpcio
pip install grpcio-tools
Copy the code
Compile the proto filepython -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. hello.proto python -m grpc_tools.protoc: The Protoc compiler for Python is implemented by python modules, so this step is very easy --python_out=. : --grpc_python_out=. : Compile generates path for grPC-related code to current directory -- i.helloworld. Proto: Path to the proto file, where the proto file is in the current directoryCopy the code
4. Generate the following files
Helloworld_pb2.py: Used to interact with protobuf data
Helloworld_pb2_grpc. py: Used to interact with GRPC
Create a new file to start the GRPC service
Server side: helloworld_grpc_server.py
From Concurrent import futures import time import GRPC import hello_pb2 import hello_pb2_grPC # implement as defined in the proto file HelloWorldServiceServicer class Greeter(hello_pb2_grpc.HelloWorldServiceServicer): Def SayHello(self, request, context): return hello_pb2.HelloResponse(message = 'hello {msg}'.format(msg = request.name)) def serve(): # start RPC service server = GRPC. Server (futures. ThreadPoolExecutor (max_workers = 10)) hello_pb2_grpc.add_HelloWorldServiceServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() try: while True: time.sleep(60*60*24) # one day in seconds except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': serve()Copy the code
Python helloworld_grpc_server.py starts the service
Once the Python server is started, listen on port 50051
5. Generate front-end code
Generate grPC-Web Client code
Under Windows, this is a bit of a hassle, so use the Win10 subsystem directly. Bash is shown below
# download protocWget HTTP: / / https://github.com/protocolbuffers/protobuf/releases/download/v3.17.3/protoc-3.17.3-linux-x86_64.zip# decompressionUnzip protoc - 3.17.3 - Linux - x86_64.zip -d protoccd protoc/
Copy protoc. Exe to path
sudo mv bin/protoc /usr/local/bin
cd.# download protoc - gen - GRPC - webWget sudo mv at https://github.com/grpc/grpc-web/releases/download/1.2.1/protoc-gen-grpc-web-1.2.1-linux-x86_64 Protoc - gen - GRPC - web - 1.2.1 - Linux - x86_64 / usr /local/bin/protoc-gen-grpc-web
Copy the code
The generated code
Js version: Protoc -i =. --js_out=import_style=commonjs:. --grpc-web_out=import_style=commonjs,mode= grpcwebText:.hello. protoc -I=. --js_out=import_style=commonjs:. --grpc-web_out=import_style=typescript,mode=grpcwebtext:. hello.protoCopy the code
Front-end project installation dependencies
yarn add grpc-web
yarn add google-protobuf
Copy the code
Dump the two generated JS files directly into node_modules
Vue template
<template>
<div className="home">
{{ message }}
</div>
</template>
<script>
import { HelloRequest } from 'hello_pb'
import { HelloWorldServicePromiseClient } from 'hello_grpc_web_pb'
export default {
name: 'Home',
data () {
return {
message: ' '}},methods: {
// Get the message (using async await)
async getMessage () {
// Note that this port is a proxy server port, not a GRPC port
var client = new HelloWorldServicePromiseClient('http://localhost:8080'.null.null)
// simple unary call
var request = new HelloRequest()
request.setName('World')
// eslint-disable-next-line handle-callback-err
const res = client.sayHello(request, {}, (err, response) = > {
// document.getElementById('response').innerHTML = response.getMessage()
})
res.then(res= > {
console.log(res)
})
}
},
mounted () {
this.getMessage()
}
}
</script>
Copy the code
6. Deploy the proxy
Since Grpc uses Http2, there is a need to deploy an agent to handle and resolve cross-domain issues
Github.com/improbable-…
Grpcwebproxy - v0.14.0 - win64. Exe - backend_addr = localhost: 50051 - run_tls_server = false - allow_all_origins
7. Run happily
Finally, you can have a pleasant interaction
I will continue to learn how to use….
Reference article:
Segmentfault.com/a/119000002…
www.fenxianglu.cn/article/285
www.jianshu.com/p/43fdfeb10…