一、protobuf
环境的配置
-
2、使用命令
go env
查看自己的go path
地址并且在go path
的目录下创建一个bin
文件夹 -
3、将第一点下载下来的东西解压出来将
bin
下面的protoc
拷贝到go path
下的bin
文件夹下 -
4、查看安装的版本
protoc --version
-
5、
protoc-gen-go
的安装(用于生成对应go
语言的micro
代码)go get -u github.com/golang/protobuf/proto go get -u github.com/golang/protobuf/protoc-gen-go
-
6、查看
go path
下的bin
目录下会有以下几个文件➜ bin tree . . ├── protoc ├── protoc-gen-g 0 directories, 2 files ➜ bin
-
7、
mac
操作系统中可以使用另外一种安装方式(推荐安装方式)ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install protobuf
protoc --version
二、编写protobuf
文件
-
1、简单的代码文件
syntax = "proto3"; option go_package = ".;proto"; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
-
2、运行脚本生成
go
文件# protoc -I . 文件名 --go_out=plugins=grpc:. protoc -I . helloWorld.proto --go_out=plugins=grpc:.
三、服务层的编写
-
1、安装依赖包
go get -u google.golang.org/grpc
-
2、服务层代码
server.go
文件package main import ( "context" "gin_stuty/07.grpc/proto" "google.golang.org/grpc" "net" ) type Server struct { } // SayHello 给结构体绑定一个方法(类似给类添加一个方法) func (s *Server) SayHello(ctx context.Context, in *proto.HelloRequest) (*proto.HelloReply, error) { return &proto.HelloReply{ Message: "hello" + in.Name, }, nil } func main() { g := grpc.NewServer() proto.RegisterGreeterServer(g, &Server{}) listen, err := net.Listen("tcp", "0.0.0.0:8088") if err != nil { panic("服务监听错误:" + err.Error()) } err = g.Serve(listen) if err != nil { panic("服务启动失败:" + err.Error()) } }
三、客户端的方法
-
1、创建一个
client.go
的文件 -
2、
client.go
的文件类似拨号连接服务器端package main import ( "context" "fmt" "gin_stuty/07.grpc/proto" "google.golang.org/grpc" ) func main() { // 开始拨号 conn, err := grpc.Dial("0.0.0.0:8088", grpc.WithInsecure()) if err != nil { panic("拨号错误:" + err.Error()) } defer conn.Close() c := proto.NewGreeterClient(conn) r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "水痕"}) if err != nil { panic("发送错误" + err.Error()) } fmt.Println("接收服务器端数据:", r.Message) }