1.编译器protoc, 下载地址:https://github.com/protocolbuffers/protobuf/releases (下载对应的版本, 解压后放到go的bin中)
2.安装golang扩展, go get -u github.com/golang/protobuf/protoc-gen-go
3.grpc库, git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/gprc
4.编写DIL文件
syntax = "proto3";
package helloworld;
// The greeting 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;
}
5.生成文件, 在IDL文件目录执行: protoc --go_out=plugins=grpc:. ./hello.proto
6.服务端代码:
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"net"
pb "IDL文件生成的hello.pb.go"
)
type service struct{} //声明一个结构体, 实现服务
func (s *service) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { //服务逻辑, 出入参要和hello.pd.go中的方法一样
name := req.Name //请求结构体中的数据
fmt.Println("this is golang service, request...", name)
return &pb.HelloReply{
Message: "this is golang service", //返回数据
}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50001")
if err != nil {
panic(err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &service{}) //注册
_ = s.Serve(lis)
}
7.客户端代码
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"hello.pb.go"
)
func main() {
conn, err := grpc.Dial("localhost:50001", grpc.WithInsecure()) //连接
if err != nil {
fmt.Println(err)
}
defer conn.Close()
hc := helloworld.NewGreeterClient(conn)
res, err := hc.SayHello(context.Background(), &helloworld.HelloRequest{
Name: "this is golang client request",
})
if err != nil {
fmt.Println(err)
}
fmt.Println("this is golang client, response...", res.Message)
}
java与go的客户端和服务端代码都完成了, 并且可以跨语言调用
跨语言通信需要注意, IDL一定要一致, IDL中的package定义也一定要一致, 是grpc服务名的一部分