Go之路(三十四):微服务之go-micro(一)
Go之路:微服务之go-micro
主要是根据这个文档来学习的,https://blog.dingkewz.com/post/
此系列不会详细说明go-micro框架,只是用于记录自己的学习历程以及技术沉淀,因为上面的文档已经写的很详细了。
go get -u google.golang.org/grpc //需要自己手动去github下载 go get -u github.com/golang/protobuf/protoc-gen-go
上面这两个是必要的准备。
一、proto文件
// consignment-service/proto/consignment/consignment.proto
syntax = "proto3";
package go.micro.srv.consignment;
service ShippingService {
rpc CreateConsignment(Consignment) returns (Response) {}
}
message Consignment {
string id = 1;
string description = 2;
int32 weight = 3;
repeated Container containers = 4;
string vessel_id = 5;
}
message Container {
string id = 1;
string customer_id = 2;
string origin = 3;
string user_id = 4;
}
message Response {
bool created = 1;
Consignment consignment = 2;
}
可以用于自动生成go文件,需要用到工具来编译它,原始的方法就是probuf里面的工具,但是go-micro自带了工具,所以编译命令如下
build:
protoc -I. --go_out=plugins=micro:$(GOPATH)/src/github.com/ewanvalentine/shipper/consignment-service \ proto/consignment/consignment.proto
build是linux下make工具的用法,可以参考这个文章
生成文件后,需要实现自己定义的接口,一般写在handler.go里面,这里就不贴了,因为主要是介绍go-micro而不是关注逻辑
在main.go文件里创建服务
package main
import (
"github.com/micro/cli"
"github.com/micro/go-micro"
_ "github.com/micro/go-plugins/registry/etcdv3"
"log"
"user-srv/handler"
"user-srv/proto"
)
func main() {
service := micro.NewService(
micro.Name("user-srv"),
micro.Version("latest"),
)
service.Init(micro.Action(func(c *cli.Context) {
log.Print("user-srv start..")
pb.RegisterUserServiceHandler(service.Server(), handler.NewUserHandler())
}),
micro.AfterStart(func() error {
log.Print("test AfterStart")
return nil
}),
micro.AfterStop(func() error {
log.Print("test AfterStop")
return nil
}),
)
log.Println("user-srv 启动成功")
if err := service.Run(); err !=nil{
log.Fatalf("err:%v",err)
}
}
可以自己创建一个client来测试接口是否符合预期
package main
import (
"fmt"
"github.com/micro/go-micro"
"golang.org/x/net/context"
"user-srv/proto"
_ "github.com/micro/go-plugins/registry/etcdv3"
)
func main() {
server := micro.NewService(
micro.Name("user-srv"),
)
server.Init()
client := pb.NewUserServiceClient("user-srv",server.Client())
res,err := client.MainHandler(context.Background(),&pb.UserRequest{Action:"create",Userid:0})
fmt.Println(res,err)
}
另外,可以使用etcd来代替consul作为服务发现
import (
_ "github.com/micro/go-plugins/registry/etcd"
)
service --registry=etcd --registry_address=127.0.0.1:2379

浙公网安备 33010602011771号