安装依赖
Go Micro
$ go get github.com/micro/go-micro
Protobuf (如果您使用代码生成,您还需要使用protoc-gen-go)
$ go get github.com/micro/protobuf/{proto,protoc-gen-go}
工具包 (Micro工具包提供了访问微服务的各种方法)
$ go get github.com/micro/micro
Docker (可用预制docker images)
$ docker pull microhq/micro
尝试CLI
运行greeter服务
$ go get github.com/micro/examples/greeter/srv && srv
服务清单
$ micro list services consul go.micro.srv.greeter
获取服务
$ micro get service go.micro.srv.greeter service go.micro.srv.greeter version 1.0.0 Id Address Port Metadata go.micro.srv.greeter-34c55534-368b-11e6-b732-68a86d0d36b6 192.168.1.66 62525 server=rpc,registry=consul,transport=http,broker=http Endpoint: Say.Hello Metadata: stream=false Request: { name string } Response: { msg string }
查询服务
$ micro query go.micro.srv.greeter Say.Hello '{"name": "John"}' { "msg": "Hello John" }
调用服务
$ micro call hello Greeter.Greet '{"name":"SngZhibin","msg":"null"}' { "name": "SngZhibin", "msg": "SngZhibin您好" } // hello是服务名 Greeter.Greet是.proto中定义的服务
创建服务实例
// demo.proto syntax = "proto3"; // 指定版本 package pb; // 包名 message Request { string name = 1; string msg = 2; } message Response { string name = 1; string msg = 2; } service Greeter { // 服务 rpc Greet (Request) returns (Response) { } }
使用protoc工具生成对应代码后服务代码
// 服务代码 package main import ( "Songzhibin/raftRealize/microDemo/pb" "context" "fmt" "github.com/micro/go-micro" ) // 自定义结构体 type server struct{} func (s server) Greet(ctx context.Context, req *pb.Request, rep *pb.Response) error { rep.Name = req.Name rep.Msg = req.Name + "您好" return nil } func main() { // 创建服务 s := micro.NewService( // micro.Name("服务名") micro.Name("hello"), ) // 初始化 s.Init() // 注册 pb.RegisterGreeterHandler(s.Server(), &server{}) err := s.Run() if err != nil { fmt.Println(err) } }
// PS: 这里遇到一个问题就是本地下载包后无法正常启动编译服务 使用go mod 正常
终端调用
$ micro call hello Greeter.Greet '{"name":"SngZhibin","msg":"null"}' { "name": "SngZhibin", "msg": "SngZhibin您好" }
代码调用
package main import ( "Songzhibin/raftRealize/microDemo/pb" "context" "fmt" "github.com/micro/go-micro" ) func main() { s := micro.NewService( // micro.Name("服务名") micro.Name("hello"), ) greeter := pb.NewGreeterClient("hello", s.Client()) rep, err := greeter.Greet(context.TODO(), &pb.Request{ Name: "Songzhibin", Msg: "null", }, ) if err != nil { fmt.Println(err) return } fmt.Printf("%#v",rep) }
http Api调用
// 先开启api $ micro api --handler=rpc // 在启动服务 // PS:服务名有要求 go.micro.api.xxx 2020-03-01 11:24:41.173184 I | Transport [http] Listening on [::]:54896 2020-03-01 11:24:41.173269 I | Broker [http] Connected to [::]:54897 2020-03-01 11:24:41.173562 I | Registry [mdns] Registering node: go.micro.api.hello-7269ef09-b1bd-40eb-b6e2-627023af0009 // 有 connect to 即可判断连接成功 // 在postman 调用 http://localhost:8080/hello/Greeter/Greet -> post // hello 服务名 Greeter 注册服务 Greet调用方法 body: { "name":"Songzhibin", "msg":"Null" } res: { "name": "Songzhibin", "msg": "Songzhibin您好" }