基于 grpc,protobuf 搭建 server/client 模型通信
发布于: 2020 年 08 月 08 日
protobuf环境配置
//安装 protobuf编译器brew install protobufprotoc --version//安装 go protobuf 插件go get -u github.com/golang/protobuf/{protoc-gen-go,proto}//安装 grpcgo get -u google.golang.org/grpc使用 protobuf来定义接口约束条件以及序列化二进制编码:
syntax = "proto3";package example;service FormatRequest { rpc DoFormat(Request) returns (Response){}}message Request{    string userid = 1;    string name=2;    double score=3;    int64 classId=4;}message Response{    bool success =1;    int32 errcodde =2;}通过 protobuf来严格定义接口约束条件,可以提供不同开发语言使用。
生成 golang库函数
protoc -I=. --go_out=plugins=grpc:. data.proto此时在目录下会生成一个 data.pb.go 的文件。
编写服务端代码
package mainimport (	"GoTest/grpcTest/example"	"context"	"log"	"net"	"google.golang.org/grpc"	"google.golang.org/grpc/reflection")const (	Port string = "9999")type FormatRequest struct{}func (fd *FormatRequest) DoFormat(ctx context.Context, in *example.Request) (out *example.Response, err error) {	log.Printf("in is %+v\n", in)	//TODO: 业务处理逻辑	out = &example.Response{Success: true}	return out, nil}func main() {	listener, err := net.Listen("tcp", ":"+Port)	if err != nil {		log.Fatalln("faile listen at :"+Port, err)	} else {		log.Println("server is listening at :" + Port)	}	rpcServer := grpc.NewServer()	example.RegisterFormatRequestServer(rpcServer, &FormatRequest{})	reflection.Register(rpcServer)	if err = rpcServer.Serve(listener); err != nil {		log.Fatalln("faile serve at :" + Port)	}}编写客户端代码:
package mainimport (	"GoTest/grpcTest/example"	"context"	"log"	"google.golang.org/grpc")const (	ADDRESS string = "localhost:9999")type singletonRPC struct {	clientRPC example.FormatRequestClient}var instance *singletonRPC//单例模式客户端连接 RPCfunc ConnectRPC() *example.FormatRequestClient {	if instance != nil {		return &instance.clientRPC	}	//因为这里没有启用安全链接,需要传人grpc.WithInsecure()表示忽略证书认证	conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())	if err != nil {		panic("Can't connect: " + ADDRESS)	}	clientRPC := example.NewFormatRequestClient(conn)	instance = &singletonRPC{clientRPC: clientRPC}	return &clientRPC}func main() {	//客户端链接 RPC	client := *ConnectRPC()	for i := 0; i <= 10000; i++ {		_, err := client.DoFormat(context.Background(), &example.Request{			Name:    "Jack",			ClassId: 66,			Score:   100,		})		if err != nil {			log.Fatalln("Do format error:" + err.Error())		}	}}
划线
评论
复制
发布于: 2020 年 08 月 08 日阅读数: 93
是老郭啊
关注
一位头发日渐稀疏的 90后 IT男 2020.04.07 加入
当你焦虑大于努力时,你将沦为焦虑本身。











 
    
评论