GRPC使用
代码地址:http//gitee.com/zqwlai/go-test/grpc
1. 定义proto
syntax = "proto3"; option java_multiple_files = true; option go_package = "./g"; package g; // The greeting service definition. service Greeter { 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 -I . --go_out=plugins=grpc:. helloworld.proto,会在g/目录下生成helloworld.pb.go
2. 服务端
//go:generate protoc -I ../helloworld --go_out=plugins=grpc:../helloworld ../helloworld/helloworld.proto
package main
import (
"github.com/go-test/grpc/g"
"log"
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
port = ":30000"
)
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *g.HelloRequest) (*g.HelloReply, error) {
return &g.HelloReply{Message: "Hello " + in.Name}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
g.RegisterGreeterServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
3. 客户端
package main
import (
"log"
"os"
"github.com/go-test/grpc/g"
"golang.org/x/net/context"
"google.golang.org/grpc"
"time"
)
const (
address = "localhost:30000"
defaultName = "world"
)
func main() {
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := g.NewGreeterClient(conn)
// Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
r, err := c.SayHello(context.Background(), &g.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
time.Sleep(5*time.Second)
}