安装 protobuf 和 protoc-gen-go 插件
安装 protobuf https://github.com/protocolbuffers/protobuf/releases
安装golang 插件
go get -u github.com/golang/protobuf/protoc-gen-go
放入 .zshrc
export GOPATH=$HOME/go
# 换成自己go代码的路径,这是我自己设置的路径
export GOBIN=$GOPATH/bin
# 也可以不加这一句,看自己需不需要
export PATH=$PATH:$GOPATH/bin
#把go下面的bin目录添加到电脑的环境变量中
查看版本
protoc --version
如图
上golang grpc 和 protobuf 代码
服务端
package main
import (
"context"
"log"
"net"
"mygrpc/users"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
type UserServer struct {
}
func (u *UserServer) UserIndex(ctx context.Context, in *users.UserIndexRequest) (*users.UserIndexResponse, error) {
log.Printf("receive users index request:page %d page_size %d", in.Page, in.PageSize)
return &users.UserIndexResponse{
Err: 0,
Msg: "success",
Data: []*users.UserEntity{
{Name: "aaaa", Age: 28},
{Name: "bbbb", Age: 1},
},
}, nil
}
func (u *UserServer) UserView(ctx context.Context, in *users.UserViewRequest) (*users.UserViewResponse, error) {
log.Printf("receive users uid request:uid %d", in.Uid)
return &users.UserViewResponse{
Err: 0,
Msg: "success",
Data: &users.UserEntity{
Name: "aaaa", Age: 28,
},
}, nil
}
func (u *UserServer) UserPost(ctx context.Context, in *users.UserPostRequest) (*users.UserPostResponse, error) {
log.Printf("receive users uid request:name %s password:%s,age:%d", in.Name, in.Password, in.Age)
return &users.UserPostResponse{
Err: 0,
Msg: "success",
}, nil
}
func (u *UserServer) UserDelete(ctx context.Context, in *users.UserDeleteRequest) (*users.UserDeleteResponse, error) {
log.Printf("receive users uid request:uid %d", in.Uid)
return &users.UserDeleteResponse{
Err: 0,
Msg: "success",
}, nil
}
func main() {
lis, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal("failed to listen", err)
}
grpcServer := grpc.NewServer()
users.RegisterUserServer(grpcServer, &UserServer{})
reflection.Register(grpcServer)
if err := grpcServer.Serve(lis); err != nil {
log.Fatal("faild to server,", err)
}
}
客户端
package main
import (
"context"
"fmt"
"log"
"mygrpc/user"
"time"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("127.0.0.1:1234", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal("did not connect", err)
}
defer conn.Close()
userClient := user.NewUserClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
userIndexResponse, err := userClient.UserIndex(ctx, &user.UserIndexRequest{
Page: 1,
PageSize: 12,
})
if err != nil {
log.Printf("user index could not greet: %v", err)
}
if 0 == userIndexResponse.Err {
log.Printf("user index success: %s", userIndexResponse.Msg)
userEntityList := userIndexResponse.Data
for _, row := range userEntityList {
fmt.Println(row.Name, row.Age)
}
} else {
log.Printf("user index error: %d", userIndexResponse.Err)
}
userViewResponse, err := userClient.UserView(ctx, &user.UserViewRequest{Uid: 1})
if err != nil {
log.Printf("user view could not greet: %v", err)
}
if 0 == userViewResponse.Err {
log.Printf("user view success: %s", userViewResponse.Msg)
userEntity := userViewResponse.Data
fmt.Println(userEntity.Name, userEntity.Age)
} else {
log.Printf("user view error: %d", userViewResponse.Err)
}
userPostReponse, err := userClient.UserPost(ctx, &user.UserPostRequest{Name: "big_cat", Password: "123456", Age: 29})
if err != nil {
log.Printf("user post could not greet: %v", err)
}
if 0 == userPostReponse.Err {
log.Printf("user post success: %s", userPostReponse.Msg)
} else {
log.Printf("user post error: %d", userPostReponse.Err)
}
userDeleteReponse, err := userClient.UserDelete(ctx, &user.UserDeleteRequest{Uid: 1})
if err != nil {
log.Printf("user delete could not greet: %v", err)
}
if 0 == userDeleteReponse.Err {
log.Printf("user delete success: %s", userDeleteReponse.Msg)
} else {
log.Printf("user delete error: %d", userDeleteReponse.Err)
}
}
user.proto
syntax = "proto3";
package user;
option go_package = "./users";
service User {
rpc UserIndex(UserIndexRequest) returns (UserIndexResponse) {}
rpc UserView(UserViewRequest) returns (UserViewResponse) {}
rpc UserPost(UserPostRequest) returns (UserPostResponse) {}
rpc UserDelete(UserDeleteRequest) returns (UserDeleteResponse) {}
}
enum EnumUserSex {
SEX_INIT = 0;
SEX_MALE = 1;
SEX_FEMALE = 2;
}
message UserEntity {
string name = 1;
int32 age = 2;
}
message UserIndexRequest {
int32 page = 1;
int32 page_size = 2;
}
message UserIndexResponse {
int32 err = 1;
string msg = 2;
repeated UserEntity data = 3;
}
message UserViewRequest {
int32 uid = 1;
}
message UserViewResponse {
int32 err = 1;
string msg = 2;
UserEntity data = 3;
}
message UserPostRequest {
string name = 1;
string password = 2;
int32 age = 3;
}
message UserPostResponse {
int32 err = 1;
string msg = 2;
}
message UserDeleteRequest {
int32 uid = 1;
}
message UserDeleteResponse {
int32 err = 1;
string msg = 2;
}
protobuf 语法
syntax = "proto3"; // PB协议版本
import "google/protobuf/any.proto"; // 引用外部的message,可以是本地的,也可以是此处比较特殊的 Any
package person; // 包名
option go_package = "./person_package"; // 生成类的包名,注意:会在指定路径下按照该包名的定义来生成文件夹
message PersonTest {
int32 id = 1; // int 类型
string name = 2; // string 类型
string email = 3;
Sex sex = 4; // 枚举类型
repeated PhoneNumber phone = 5; // 引用下面定义的 PhoneNumber 类型的 message
map<string, string> tags = 6; // map 类型
repeated google.protobuf.Any details = 7; // 使用 google 的 any 类型
// 定义一个枚举
enum Sex {
DEFAULT = 0;
MALE = 1;
Female = 2;
}
// 定义一个 message
message PhoneNumber {
string number = 1;
PhoneType type = 2;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
}
}
protobuf语法详细教程相关链接:
proto文件,option go_package = "./users"; ,会生成 users文件夹,以及package 为 users 的包
生成代码
protoc -I . users.proto --go_out=plugins=grpc:.
protoc -I . --go_out=plugins=grpc:. ./users/users.proto
protoc -I . proto.proto --go_out=plugins=grpc:.
protoc:表示调用protoc进行代码生成
-I:表示对应搜索路径(import)
. :代表当前路径
proto.proto:表示在路径下搜索的文件
--go_out=:表示生成代码格式(也可以是java_out等)
plugins=:表示对应插件这里是grpc,可以不写(protoc -I . proto.proto --go_out=:. )
:. :表示生成路径
测试
目录
服务端:
go run server/main.go
客户端:
go run client/main.go
新版本 postman 也支持 grpc调试了
|