1 进入https://github.com/google/protobuf/releases获取特定release版本的安装包
2 解压
tar xzvf protobuf-all-3.5.1.tar.gz
3 配置
cd protobuf-3.5.1 && ./configure
4 编译
make
如上图所以编译成功。
5 安装
make install
6 支持go语言
go get -a github.com/golang/protobuf/protoc-gen-go
8 例子:
syntax = "proto3";
option java_package = "io.grpc.examples";
package helloworld;
// The greeter service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
运行编译命令
protoc --go_out=. *.proto
得到文件hellopb.go,这是规定message的文件
下面是服务端(go):
package main
import (
"net"
pb "hello" // 引入编译生成的包
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
)
const (
// Address gRPC服务地址
Address = "127.0.0.1:8080"
)
// 定义helloService并实现约定的接口
type helloService struct{}
// HelloService ...
var HelloService = helloService{}
func (h helloService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
resp := new(pb.HelloReply)
resp.Message = "Hello " + in.Name + "."
return resp, nil
}
func main() {
listen, err := net.Listen("tcp", Address)
if err != nil {
grpclog.Fatalf("failed to listen: %v", err)
}
// 实例化grpc Server
s := grpc.NewServer()
// 注册HelloService
pb.RegisterGreeterServer(s, HelloService)
grpclog.Println("Listen on " + Address)
s.Serve(listen)
}
客户端(go):
package main
//client.go
import (
"log"
"os"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "hello"
)
const (
address = "localhost:8080"
defaultName = "Kity"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatal("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
log.Fatal("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}
9 问题
1)包太旧——由于更新了protoc,而go的包没有更新导致
hello/hello.pb.go:115: undefined: grpc.SupportPackageIsVersion4
hello/hello.pb.go:135: c.cc.Invoke undefined (type *grpc.ClientConn has no field or method Invoke)
方案:更新go包,并重新生成message文件hello.pb.go
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
2) grpc包太旧
hello/hello.pb.go:115: undefined: grpc.SupportPackageIsVersion4
hello/hello.pb.go:135: c.cc.Invoke undefined (type *grpc.ClientConn has no field or method Invoke)
方案:因为墙的原因,从github上的镜像获取包,再移动到包对应的位置
go get -u github.com/grpc/grpc-go
mv /opt/goHome/workspace/src/github.com/grpc/grpc-go /opt/goHome/src/google.golang.org/grpc
同样方式更新三个包
github.com/golang/text
github.com/golang/sys
github.com/golang/net