02ab502de54198625802f1a33950c11aaa681e93.svn-base 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/hashicorp/consul/api"
  6. "github.com/longjoy/micro-go-course/section14/register/discovery"
  7. "log"
  8. )
  9. type Service interface {
  10. HealthCheck() string
  11. DiscoveryService(ctx context.Context, serviceName string) ([]*api.AgentService, error)
  12. }
  13. var ErrNotServiceInstances = errors.New("instances are not existed")
  14. type RegisterServiceImpl struct {
  15. discoveryClient *discovery.DiscoveryClient
  16. }
  17. func NewRegisterServiceImpl(discoveryClient *discovery.DiscoveryClient) Service {
  18. return &RegisterServiceImpl{
  19. discoveryClient:discoveryClient,
  20. }
  21. }
  22. func (service *RegisterServiceImpl) DiscoveryService(ctx context.Context, serviceName string) ([]*api.AgentService, error) {
  23. instances, err := service.discoveryClient.DiscoverServices(ctx, serviceName)
  24. if err != nil {
  25. log.Printf("get service info err: %s", err)
  26. }
  27. if instances == nil || len(instances) == 0 {
  28. return nil, ErrNotServiceInstances
  29. }
  30. return instances, nil
  31. }
  32. func (*RegisterServiceImpl) HealthCheck() string {
  33. return "OK"
  34. }