go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
go get -u google.golang.org/grpc
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
git clone git@github.com:googleapis/go-genproto.git $GOPATH/src/google.golang.org/genproto
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"demo/rpc/grpc/simple/protos/pb"
)
const (
port = "localhost:9090"
)
type server struct{}
func (s *server) Echo(ctx context.Context, in *pb.StringMessage) (*pb.StringMessage, error) {
log.Printf("Received: %v", in.Value)
return &pb.StringMessage{Value: "Hello " + in.Value}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterYourServiceServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/grpc"
"demo/rpc/grpc/simple/protos/pb"
)
const (
address = "localhost:9090"
defaultName = "world"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewYourServiceClient(conn)
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.Echo(ctx, &pb.StringMessage{Value: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Value)
}
syntax = "proto3";
option go_package = "/pb";
package example;
message StringMessage {
string value = 1;
}
service YourService {
rpc Echo(StringMessage) returns (StringMessage) {}
}
protoc --go_out=./protos --go-grpc_out=./protos --proto_path=./protos protos/*.proto
这时 protos/ 目录下会生成 helloworld.pb.go 和 helloworld_grpc.pb.go 文件,该文件是 grpc 接口以及相关参数的定义
2019/06/25 17:32:09 Received: world
2019/06/25 17:32:09 Greeting: Hello world