工具下载
-
- https://github.com/protocolbuffers/protobuf/releases/download/v3.13.0/protoc-3.13.0-win64.zip
- Window 下安装:
- Linux 安装
tar -xvf protobuf cd protobuf ./configure --prefix=/usr/local/protobuf make make check make install ``` - 如遇报错,则需升级gcc: - error: unrecognized command line option "-std=c++11"
-
protoc-gen-go
- go get github.com/golang/protobuf
- protoc-gen-go提供了protoc编译器生成go相关api的实现,其位github.com/golang/protobuf库下。
- protobuf库是protocol buffers协议的golang语言版实现。protoc编译器编译时需依赖它。
- go get github.com/golang/protobuf
-
protoc-gen-micro
protos
- Users.proto
syntax = "proto3";
package Models;
option go_package = "./;Models";
message UserModel {
// @inject_tag: json:"uid"
int32 UserID = 1;
// @inject_tag: json:"name"
string Name = 2;
}
- UserService.proto
syntax = "proto3";
package Models;
option go_package = "./;Models";
import "Users.proto";
message UsersRequest {
int32 size = 1;
}
message UserListResponse {
repeated UserModel data=1;
}
service UserListService {
rpc GetUserList(UsersRequest) returns (UserListResponse);
}
根据proto生成相关go文件
cd ../models/protos
protoc.exe --micro_out=../ --go_out=../ ./Users.proto
protoc.exe --micro_out=../ --go_out=../ ./UserService.proto
protoc-go-inject-tag.exe -input=../Users.pb.go
Client
package main
import (
"context"
"fmt"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-micro/v2/registry/etcd"
Models "go-micro-service/models"
"log"
)
func main() {
server := micro.NewService(
micro.Name("user.client"),
micro.Registry(etcd.NewRegistry(
registry.Addrs("127.0.0.1:2379"),
)),
)
userServiceClient := Models.NewUserListService("user.server", server.Client())
resp, e :=userServiceClient.GetUserList(context.Background(), &Models.UsersRequest{Size: 5})
if e!=nil {
log.Fatal(e)
}
fmt.Println(resp)
for r := range resp.Data {
fmt.Println(resp.Data[r].UserID, resp.Data[r].Name)
}
}
Server
package main
import (
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-micro/v2/registry/etcd"
Models "go-micro-service/models"
"go-micro-service/service"
)
func main() {
reg := etcd.NewRegistry(
registry.Addrs("127.0.0.1:2379"),
)
server:=micro.NewService(
micro.Name("user.server"),
micro.Registry(reg),
)
server.Init()
Models.RegisterUserListServiceHandler(server.Server(), new(service.UserService))
server.Run()
}
源码地址
- https://github.com/AngelovLee/GoMicroService/releases/tag/1.0.0