grpc流程
1、下载安装包
安装protobuf
go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go
安装gRPC
go get -u google.golang.org/grpc
不过由于国内的网络原因上面的命令可能不会成功
执行下面的多条命令来代替
git clone https://github.com/golang/net.git =>$GOPATH/src/golang.org/x/net
git clone https://github.com/golang/text.git =>$GOPATH/src/golang.org/x/text
git clone https://github.com/google/go-genproto.git =>$GOPATH/src/google.golang.org/genproto
git clone https://github.com/grpc/grpc-go.git =>$GOPATH/src/google.golang.org/grpc
git clone https://github.com/protocolbuffers/protobuf-go.git =>$GOPATH/src/google.golang.org/protobuf
注:go版本再1.5以上
2、protobuf文件
helloword.proto
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply){}
}
message HelloRequest{
string name = 1;
}
message HelloReply{
string message = 1;
}
3、编译protobuf 文件
protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
-I path1 path2 --go_out=plugins=grpc:path3
path1:搜索哪个目录(当前目录的相对路径)
path2:使用哪个proto文件(当前目录的相对路径)
path3:编译转换的.go文件放置的路径(当前目录的相对位置)
使用docker编译
docker run namely/protoc-all
docker run -v ${PWD}:/defs namely/protoc-all -o interface -f proto/user.proto -l go
-o 指定输出文件
-f 指定proto文件
https://github.com/namely/docker-protoc
4、服务端编写
package main
import (
"context"
fmt "fmt"
"google.golang.org/grpc"
"grpc_test/helloworld"
"net"
)
type server struct{}
// 实现接口
func (s *server)SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error){
r := helloworld.HelloReply{}
fmt.Println(in.Name)
r.Message = fmt.Sprintf("hello %s", in.Name)
return &r,nil
}
const listen_port = "127.0.0.1:50021"
func main(){
// net.listen监听
listen,err := net.Listen("tcp",listen_port)
if err != nil{
fmt.Println("listen fail")
}
//new server
s := grpc.NewServer()
//register server 注:context.Background()是空context
helloworld.RegisterGreeterServer(s,&server{})
// 接收处理
err = s.Serve(listen)
if err != nil{
fmt.Println("server fail")
}
}
5、客户端编写
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpc_test/helloworld"
)
const conn_port = "127.0.0.1:50021"
func main(){
// 建立连接
conn,err := grpc.Dial(conn_port,grpc.WithInsecure())
if err != nil{
fmt.Println("con fail")
}
// 获取客户端对象
client := helloworld.NewGreeterClient(conn)
// 客户端处理
res,err := client.SayHello(context.Background(),&helloworld.HelloRequest{
Name: "lqh",
})
if err != nil{
fmt.Println("sayhello fail")
}
fmt.Println(res)
}