//声明proto的版本 只有 proto3 才支持 gRPC
syntax = "proto3";
// 将编译后文件输出在 github.com/lixd/grpc-go-example/helloworld/helloworld 目录
option go_package = "./";
// 指定当前proto文件属于helloworld包
// service 关键字定义提供的服务
service MyService {
// 定义一个批量查询 user 的方法
rpc User (UserReq) returns (UserReply){
}
rpc Add (Params) returns (Result){
}
}
message Params{
int32 numOne=1;
int32 numTwo=2;
}
message Result{
int32 data = 1;
}
go执行生成命令
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative api.proto
go代码
package main
import (
"context"
"fmt"
"log"
"time"
api "RPC/api"
"google.golang.org/grpc"
)
const (
address = "localhost:50051"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("连接失败: %v", err)
}
defer conn.Close()
c := api.NewMyServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
fmt.Println("")
add, err := c.Add(ctx, &api.Params{NumOne: 3, NumTwo: 4})
if err != nil {
log.Fatalf("远程调用请求失败: %v", err)
}
fmt.Printf("Add远程调用结果为: %+v", add.Data)
}
python生成命令
python -m grpc_tools.protoc -I ./ --python_out=. --grpc_python_out=. ./api.proto
python代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from concurrent import futures
import grpc
import api_pb2_grpc, api_pb2
from api_pb2_grpc import MyServiceServicer
class Service(MyServiceServicer):
def Add(self, request, context):
print(request.numOne)
print(request.numTwo)
a=request.numOne
b=request.numTwo
res=0
res=a+b
print(res)
return api_pb2.Result(data=res)
def serve():
print('start grpc server====>')
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
api_pb2_grpc.add_MyServiceServicer_to_server(Service(), server)
server.add_insecure_port('[::]:59988')
server.start()
#while 1:
# time.sleep(10)
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()