grpc支持多种语言, 也支持Golang
安装:
由于无法直接获取对应的包, 因此安装需要费点功夫折腾下
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
# 下载grpc-go
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
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
# 安装
cd $GOPATH/src/
go install google.golang.org/grpc
备注:
1.github.com/golang/protobuf/{proto,protoc-gen-go}
可以直接下载访问github.com/golang/protobuf
下载对应文件
2.net/text包可以不用下载,默认应该有,若没有,则下载,可不用放入golang.org/x/
下, 可以引用即可
3.安装过程若执行不成功, 建议手动clone github文件,并将其放入到$GOPATH/src/golang.org 对应的目录下
4.proto 需加入path,方便进行命令执行
net/context 放入$GOPATH/src/golang.org/x
proto,protoc-gen-go 放入$GOPATH/src/google.golang.org/genproto
grpc 放入$GOPATH/src/google.golang.org/grpc
定义proto文件:
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;
}
转换go文件:
protoc --go_out=plugins=grpc:. helloworld.proto
helloword入门
服务端server.go:
package main
import (
"log"
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "sr/helloworld"
)
const (
port = ":50051"
)
type server struct {}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest