brew install consul
consul agent -dev
consul
├── consul
│ └── main.go
├── mdns
│ └── main.go
└── proto
├── build.sh
├── greeter.micro.go
├── greeter.pb.go
└── greeter.proto
consul/mdns/main.go
的代码和srv中的server/main.go
几乎是一模一样的
go run consul/mdns/main.go
2019/06/23 20:05:10 Transport [http] Listening on [::]:58616
2019/06/23 20:05:10 Broker [http] Connected to [::]:58617
2019/06/23 20:05:10 Registry [mdns] Registering node: go.micro.srv.greeter-cc5d6b85-7b82-40a8-9e9a-a2c0468d6c17
可以看到 go-micro 默认使用的是 mdns 进行的服务发现
MICRO_REGISTRY=consul go run main.go
go run main.go --registry=consul
package main
import (
"context"
"github.com/cheerego/go-micro-in-action/consul/proto"
"github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/consul"
"log"
)
type Greeter struct{}
func (s *Greeter) Hello(ctx context.Context, req *greeter.Request, rsp *greeter.Response) error {
log.Print("Received Say.Hello request")
rsp.Greeting = "Hello " + req.Name
return nil
}
func main() {
service := micro.NewService(
micro.Name("go.micro.srv.greeter"),
micro.Registry(consul.NewRegistry(func(options *registry.Options) {
options.Addrs = []string{
"127.0.0.1:8500",
}
})),
)
// optionally setup command line usage
service.Init()
// Register Handlers
greeter.RegisterGreeterHandler(service.Server(), new(Greeter))
// Run server
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
micro.Registry(consul.NewRegistry(func(options *registry.Options) {
options.Addrs = []string{
"127.0.0.1:8500",
}
})),
2019/06/23 20:08:58 Transport [http] Listening on [::]:58650
2019/06/23 20:08:58 Broker [http] Connected to [::]:58651
2019/06/23 20:08:58 Registry [consul] Registering node: go.micro.srv.greeter-4e2b4996-0904-4105-8a10-f741e6b99c67