1, the installation protobuf
grpc
Use protobuf
as IDL(interface descriton language)
, and requires protobuf 3.0
more, here we choose direct current version 3.8, git Download .
Select the operating system to download the corresponding version, here we directly use the already compiled protoc
executable file (or download the package compiled and installed).
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.8.0-rc1/protoc-3.8.0-rc-1-linux-x86_64.zip tar -zxvf protoc-3.8.0-rc-1-linux-x86_64.zip mv protoc-3.8.0-rc-1-linux-x86_64 /usr/local/protoc ln -s /usr/local/protoc/bin/protoc /usr/local/bin/protoc #查看 protoc protoc --version
2, mounting protoc-gen-go
go get -u github.com/golang/protobuf/protoc-gen-go
3, installation grpc-go library
git clone https://github.com/grpc/grpc-go.git $ GOPATH / src / google.golang.org / grpc git clone https://github.com/golang/net.git $ GOPATH / src / golang .org / x / net git clone https://github.com/golang/text.git $ GOPATH / src / golang.org / x / text git clone https://github.com/google/go-genproto.git $ GOPATH / src / google.golang.org / genproto cd $ GOPATH / src / go install google.golang.org/grpc
4, edit proto file
= syntax "proto3"; // User package Package User; // the specified package path and package names of go // Option go_package = "App / Services; Services"; // specified namespace php // option php_namespace = "App \\ services "; defined // User interface services and service -service the User { RPC UserIndex (UserIndexRequest) Returns (UserIndexResponse) {} RPC userview (UserViewRequest) Returns (UserViewResponse) {} RPC UserPost (UserPostRequest) Returns (UserPostResponse) {} UserDelete RPC (UserDeleteRequest) Returns (UserDeleteResponse) {} } // enum type emun EnumUserSex { SEX_INIT = 0; // 0 enumerated type must start SEX_MALE =. 1; SEX_FEMALE = 2; } // user entity model userEntity {Message String name =. 1; Int32 Age = 2; } // User service requests each interface / response structure Message UserIndexRequest { Int32 Page =. 1; Int32 PAGE_SIZE = 2; } Message UserIndexResponse { Int32 = ERR. 1; String MSG = 2; // return a list of object data userEntity REPEATED userEntity data =. 3; } Message UserViewRequest { Int32 = UID. 1; } Message UserViewResponse { Int32 = ERR. 1; String MSG = 2; // return a userEntity objects 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; }
5, generates the interface library
# Load protoc-gen-go server-side plug-in generates go grpc's / Client # Note To install the protoc-gen-go plug protoc -I --go_out = plugins = grpc: . ./ user user.proto
6, server-side
package main import ( "context" "log" "net" "rpc/grpc/user" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ) //UserServer 实现User服务的业务对象 type UserServer struct { } //UserIndex 实现了User 服务接口的所有方法 func (u *UserServer) UserIndex(ctx context.Context, in *user.UserIndexRequest) (*user.UserIndexResponse, error) { log.Printf("receive user index request:page %d page_size %d", in.Page, in.PageSize) return &user.UserIndexResponse{ Err: 0, Msg: "success", Data: []*user.UserEntity{ {Name: "aaaa", Age: 28}, {Name: "bbbb", Age: 1}, }, }, nil } //UserView 获取详情 func (u *UserServer) UserView(ctx context.Context, in *user.UserViewRequest) (*user.UserViewResponse, error) { log.Printf("receive user uid request:uid %d", in.Uid) return &user.UserViewResponse{ Err: 0, Msg: "success", Data: &user.UserEntity{ Name: "aaaa", Age: 28, }, }, nil } //UserPost 提交数据 func (u *UserServer) UserPost(ctx context.Context, in *user.UserPostRequest) (*user.UserPostResponse, error) { log.Printf("receive user uid request:name %s password:%s,age:%d", in.Name, in.Password, in.Age) return &user.UserPostResponse{ Err: 0, Msg: "success", }, Nil } // delete data UserDelete FUNC (U * UserServer) UserDelete (CTX context.Context, in user.UserDeleteRequest *) (* user.UserDeleteResponse, error) { log.Printf ( "the receive Request User UID: UID% D" , in.Uid) return {& user.UserDeleteResponse the Err: 0, Msg: "Success", }, nil } FUNC main () { LIS, ERR: = net.Listen ( "TCP", ": 1234") IF ERR! {nil = log.Fatal ( "failed the to the listen", ERR) } // create rpc service grpcServer: = grpc.NewServer () // registered for the User service User service business will achieve bound to the RPC server user.RegisterUserServer ( grpcServer, & UserServer {}) // reflective registration service that is used by CLI, the service itself has nothing to do with the reflection.Register(grpcServer) if err := grpcServer.Serve(lis); err != nil { log.Fatal("faild to server,", err) } }
7, client
package main import ( "context" "fmt" "log" "rpc/grpc/user" "time" "google.golang.org/grpc" ) func main() { //建立链接 conn, err := grpc.Dial("127.0.0.1:1234", grpc.WithInsecure()) if err != nil { log.Fatal("did not connect", err) } defer conn.Close() userClient := user.NewUserClient(conn) //设定请求超时时间 3s ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) defer cancel() //UserIndex 请求 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) // 包含 UserEntity 的数组列表 userEntityList := userIndexResponse.Data for _, row := range userEntityList { fmt.Println(row.Name, row.Age) } } else { log.Printf("user index error: %d", userIndexResponse.Err) } // UserView 请求 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) } // UserPost 请求 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) // request UserDelete } 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) } }
7, start the service / service request
go run server.go go run client.go
operation result: