1.編譯器protoc, 下載地址:https://github.com/protocolbuffers/protobuf/releases (下載對應的版本, 解壓後放到go的bin中)java
2.安裝golang擴展, go get -u github.com/golang/protobuf/protoc-gen-gogit
3.grpc庫, git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/gprcgithub
4.編寫DIL文件golang
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.客戶端代碼tcp
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服務名的一部分