go-micro学习一
1 . windows下consul安装,直接下载,将exe文件加入到path中,然后执行:
consul agent -dev
go-micro默认使用consul作为服务发现
2 .安装go-micro编译插件
go get -u github.com/micro/protobuf/proto
go get -u github.com/micro/protobuf/protoc-gen-go
3 .编译
protoc -I . --go_out=plugins=micro:./ ./proto/consignment/consignment.proto
4.proto 文件
service ShippingService {
// 托运一批货物
rpc CreateConsignment (Consignment) returns (Response) {
}
// 查看托运货物的信息
rpc GetConsignments (GetRequest) returns (Response) {
}
}
5.编写服务端
/这块代码作为服务端真实实现代码来使用
type Repository struct {
consignments []*pb.Consignment
}
func (repo *Repository) Create(consignment *pb.Consignment) (*pb.Consignment, error) {
repo.consignments = append(repo.consignments, consignment)
return consignment, nil
}
type service struct {
repo Repository
}
// 实现 consignment.pb.go 中的 ShippingServiceHandler 接口
// 托运新的货物
//
func (s *service) CreateConsignment(ctx context.Context, req *pb.Consignment, resp *pb.Response) error {
// 接收承运的货物
consignment, err := s.repo.Create(req)
if err != nil {
return err
}
resp = &pb.Response{Created: true, Consignment: consignment}
return nil
}
func main() {
server := micro.NewService(
micro.Name(" ShippingService"),
micro.Version("latest"),
)
// 解析命令行参数
server.Init()
repo := Repository{}
pb.RegisterShippingServiceHandler(server.Server(), &service{repo})
if err := server.Run(); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
6.编写客户端
func main() {
sercice := micro.NewService(micro.Name(" ShippingService"))
sercice.Init()
// 创建微服务的客户端,简化了手动 Dial 连接服务端的步骤
client := pb.NewShippingServiceClient(" ShippingService", sercice.Client())
// 在命令行中指定新的货物信息 json 件
infoFile := DEFAULT_INFO_FILE
if len(os.Args) > 1 {
infoFile = os.Args[1]
}
// 解析货物信息
consignment, err := parseFile(infoFile)
if err != nil {
log.Fatalf("parse info file error: %v", err)
}
// 调用 RPC
// 将货物存储到我们自己的仓库里
resp, err := client.CreateConsignment(context.Background(), consignment)
if err != nil {
log.Fatalf("create consignment error: %v", err)
}
// 新货物是否托运成功
log.Printf("created: %t", resp.Created)
log.Printf("resp: %v", resp)
// 列出目前所有托运的货物
resp, err = client.GetConsignments(context.Background(), &pb.GetRequest{})
if err != nil {
log.Fatalf("failed to list consignments: %v", err)
}
for _, c := range resp.Consignments {
log.Printf("%+v", c)
}
}
至此初始代码运行成功