Interface

Registry has two interface, the Registrar is for services’ register and deregister, the Discovery is for fetching the list of services.

  1. type Registrar interface {
  2. // register the service
  3. Register(ctx context.Context, service *ServiceInstance) error
  4. // deregister the service
  5. Deregister(ctx context.Context, service *ServiceInstance) error
  6. }
  1. type Discovery interface {
  2. // fetch the service list of serviceName
  3. Fetch(ctx context.Context, serviceName string) ([]*ServiceInstance, error)
  4. // subscribe to a list of serviceName
  5. Watch(ctx context.Context, serviceName string) (Watcher, error)
  6. }

Implementations: consul etcd k8s

Usage

Register a Service

Create a Registrar(e.g. consul) and inject it to Kratos applications. Then the framework will do register and deregister automatically.

  1. import consul "github.com/go-kratos/consul/registry"
  2. import "github.com/hashicorp/consul/api"
  3. cli, err := api.NewClient(api.DefaultConfig())
  4. if err != nil {
  5. panic(err)
  6. }
  7. reg := consul.New(cli)
  8. app := kratos.New(
  9. kratos.Name(Name),
  10. kratos.Version(Version),
  11. kratos.Metadata(map[string]string{}),
  12. kratos.Logger(logger),
  13. kratos.Server(
  14. hs,
  15. gs,
  16. ),
  17. kratos.Registrar(reg),
  18. )

Service Discovery (gRPC)

Create a Registrar(e.g. consul), create an Endpoint with url format as <schema>://[namespace]/<service-name>, then use grc.WithDiscovery and grpc.WithEndpoint as the options of the Dial method to get the gRPC connection.

  1. import "github.com/go-kratos/kratos/transport/http"
  2. import "github.com/go-kratos/kratos/v2/transport/grpc"
  3. cli, err := api.NewClient(api.DefaultConfig())
  4. if err != nil {
  5. panic(err)
  6. }
  7. dis := consul.New(cli)
  8. endpoint := "discovery://default/provider"
  9. conn, err := grpc.Dial(context.Background(), grpc.WithEndpoint(endpoint), grpc.WithDiscovery(dis))
  10. if err != nil {
  11. panic(err)
  12. }