13

记录go-python微服务实践,希望能帮助需要的人

 4 years ago
source link: https://studygolang.com/articles/24862
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文讲述如何使用 grpc,由 go 作为客户端,python 作为服务端进行通信。 (题外:一直迷惑于怎样让他们两个连起来,后来才发现只要对同一个proto文件进行编译就好了。。。:sweat:)

实现功能

python 实现方法 f(name) ,返回 "hello "+name,由 go 调用得到返回值

安装配置

Go

  • 个人配置是 go 1.12 ,使用 go mod 项目管理
  • 因为有些包会被墙,所有要配置 GOPROXY ,我配置的是阿里的 GOPROXY="https://mirrors.aliyun.com/goproxy/"

安装 grpc,protobuf编译器和对应的 go 插件

go get google.golang.org/grpc
go get github.com/golang/protobuf/proto
go get github.com/golang/protobuf/proto-gen-go
复制代码

注:如果在 goland 编译器里使用命令行也需要配置代理

python3

同样也是安装 grpc,protobuf等

pip3 install grpcio
 pip3 install protobuf
 pip3 install grpcio-tools 
复制代码

开始

我使用的是 goland 编译器,然后引入了 python 解释器

j6j2q2q.png!web

在红框内选择自己解释器就好

项目结构

本人初尝,可能不规范,敬请指正

-project
 -go
  -main.go
 -micro
  -hello.proto
 -python
  -server.py
复制代码

这是所需要自己创建的目录和文件,go 包内即 go代码,micro是微服务配置文件,python包是python代码

micro包

首先创建proto文件--hello.proto

syntax = "proto3"; //选择版本

package micro; // 包

service Greeter {
    rpc SayHello (HelloRequest) returns (HelloReply) {
    }
}

message HelloRequest {
    string name = 1;
}

message HelloReply {
    string msg = 1;
}
复制代码

注:这里package 要与当前路径一致

并没有很详细解释 proto 语法,大家又需要可以自行查看

编译 proto文件 首先命令行移动到 micro 包下,然后分别执行 go 和 python 的编译语句

go: hello.proto 即为需要编译的文件,编译后会在当前包下生成 hello.pb.go 文件

protoc --go_out=plugins=grpc:. hello.proto
复制代码

python:编译后会生成 hello_pb2.pyhello_pb2_grpc.py 两个文件

python3 -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. hello.proto
复制代码

文件都生成成功的话就可以编写客户端和服务端代码了

python服务端

在 python 包下 server.py 文件内编写如下代码

from concurrent import futures
import time
import grpc
from micro import hello_pb2
from micro import hello_pb2_grpc


class Greeter(hello_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return hello_pb2.HelloReply(msg = "hello "+request.name)

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers = 10))
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(),server)
    server.add_insecure_port('[::]:50051')
    print("服务启动")
    server.start()
    try:
        while True:
            time.sleep(60*60*24)
    except KeyboardInterrupt:
        server.stop(0)

if __name__=='__main__':
    serve()
复制代码

创建了端口号为 50051 的服务 可以尝试启动一下服务

go 客户端

在go 包下 main.go 中编写下面代码

package main

import (
	"context"
	pb "cymdemo/micro"
	"fmt"
	"google.golang.org/grpc"
)

const address  = "localhost:50051"

func main()  {
	conn,err := grpc.Dial(address,grpc.WithInsecure())
	if err != nil {
		fmt.Println(err)
	}
	defer conn.Close()

	c := pb.NewGreeterClient(conn)
	name := "world"
	res,err := c.SayHello(context.Background(),&pb.HelloRequest{Name:name})

	if err != nil{
		fmt.Println(err)
	}
	fmt.Println(res.Msg)
}
复制代码

先启动 python 服务端,然后启动 go 客户端就会拿到调用结果

hello world
复制代码

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK