标签:本地 -- 判断 微服务 example 代码生成 address dock str
$ go get github.com/micro/go-micro
$ go get github.com/micro/protobuf/{proto,protoc-gen-go}
$ go get github.com/micro/micro
$ docker pull microhq/micro
$ 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) { } }
// 服务代码 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) }
// 先开启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您好" }
标签:本地 -- 判断 微服务 example 代码生成 address dock str
原文地址:https://www.cnblogs.com/binHome/p/12381511.html