目錄結構
grpc (根目錄)
|-- server.go
|-- client.go
|-- go.mod
|-- helloworld
|---- helloworld.proto
|---- helloworld.pb.go
環境
初始化 go module
go mod init server
安裝 Protocol
安裝該協議編譯器用來生成 gRPC 服務程式碼。https://github.com/google/protobuf/releases下載
tar -xvf protobuf-all-3.13.0.tar.gz
cd protobuf-3.13.0
./configure –prefix=/usr/local/
sudo make #要編譯很久
sudo make check
sudo make install
make install
後可能出錯
protoc: error while loading shared libraries: libprotoc.so.24: cannot open shared object file: No such file or directory
執行下ldconfig
即可
然後protoc --version
正常可輸出版本後,環境就準備好了
訊息體
建立helloworld.proto
syntax = "proto3";
package helloworld;
// 服務端定義
service Greeter {
// 服務端返饋資訊方法
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// 包含使用者名稱的請求資訊
message HelloRequest {
string name = 1;
}
// 服務端響應資訊
message HelloReply {
string message = 1;
}
然後使用protoc命令,執行以下命令生成helloworld.pb.go
protoc --proto_path=helloworld --go_out=plugins=grpc:helloworld helloworld/helloworld.proto
服務端
server.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"log"
"net"
pb "server/helloworld"
)
const (
port = ":50051"
)
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.Name)
return &pb.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()
pb.RegisterGreeterServer(s, &server{})
fmt.Println("啟動服務",port)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
啟動服務端服務go run server.go
客戶端
client.go
package main
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"os"
pb "server/helloworld"
)
const (
address = "localhost:50051"
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 := pb.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(), &pb.HelloRequest{Name: name})
log.Print(r)
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}
啟動客戶端服務go run client.go
- Go新手,有錯誤的地方幫忙指正,感謝。
本作品採用《CC 協議》,轉載必須註明作者和本文連結