1、安裝proto
下載 Windows 版本
打開官方發布頁面
訪問 Protocol Buffers 的 GitHub Releases 頁面:
👉 https://github.com/protocolbuffers/protobuf/releases
解壓 ZIP 文件
將下載的 ZIP 文件解壓到一個你容易找到的目錄,例如:
C:\protoc\
解壓后你會看到類似結構:
└── bin└── protoc.exe
└── include└── google\protobuf\...
將 protoc.exe 添加到系統 PATH 環境變量
- 按下 Win + S,搜索 “環境變量” → 選擇 “編輯系統環境變量”。
- 點擊 “環境變量” 按鈕。
- 在 “系統變量” 區域,找到并選中 Path,點擊 “編輯”。
- 點擊 “新建”,然后添加 protoc.exe 所在的路徑,例如
protoc --version# 出現類似這樣的提示,說明安裝成功
libprotoc 31.1
驗證安裝
2、小實例
編寫proto文件user.proto
syntax = "proto3";//版本
package user; //默認包
option go_package ="./user"; //包名service User{//定義rpc方法rpc GetUser(UserRequest) returns (UserResponse);}
//消息體,可以看成結構體
message UserRequest{// 屬性的類型,屬性名=標識符string id = 1;
}message UserResponse{string id = 1;string name = 2;string phone = 3;
}
服務端
package mainimport ("context""fmt""go_collect/grpc/proto/user""google.golang.org/grpc""net"
)type UserServer struct {user.UnimplementedUserServer
}func (u *UserServer) GetUser(cxt context.Context, req *user.UserRequest) (*user.UserResponse, error) {res := &user.UserResponse{Id: "1",Name: "張三",Phone: "13812345678",}return res, nil
}
func main() {listen, err := net.Listen("tcp", ":8088")if err != nil {fmt.Println("監聽失敗", err)return}server := grpc.NewServer()user.RegisterUserServer(server, new(UserServer))fmt.Println("GRPC服務端,已經啟動了!")server.Serve(listen)
}
客戶端
package mainimport ("context""fmt""go_collect/grpc/proto/user""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure"
)func main() {// Dial參數 第一個是地址,第二個數據是否加密conn, err := grpc.Dial("127.0.0.1:8088", grpc.WithTransportCredentials(insecure.NewCredentials()))if err != nil {fmt.Println("客戶端遠程連接失敗")return}defer conn.Close()userClient := user.NewUserClient(conn)// 調用方法res, err := userClient.GetUser(context.Background(), &user.UserRequest{Id: "1",})if err != nil {fmt.Println("客戶端調用遠程方法失敗")return}fmt.Println(res)}
編譯命令
編譯命令
protoc --go-grpc_out=:. --go_out=. ./user.proto
參數 | 功能 |
---|---|
protoc | Protocol Buffers 的官方編譯器,用于將 .proto 文件編譯成目標語言的源代碼 |
–go-grpc_out=:. | 指定生成 gRPC 服務的 Go 代碼(即服務端和客戶端的 stub),*_grpc.pb.go 文件 |
–go_out=. | 生成 Protocol Buffers 消息結構體的 Go 代碼(即數據結構、序列化/反序列化方法),*.pb.go |
./user.proto | 指定輸入的 .proto 文件路徑。 |
項目結構
啟動服務端
客戶端獲取
protobuf 底層數據實現原理
grpc服務鏈接原理分析