eee44c8517a0eb0f9765a80bc6994ef30da9fc4a.svn-base 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package discovery
  2. import (
  3. "context"
  4. "github.com/go-kit/kit/log"
  5. "github.com/go-kit/kit/sd"
  6. "github.com/go-kit/kit/sd/consul"
  7. "github.com/hashicorp/consul/api"
  8. "os"
  9. "strconv"
  10. )
  11. type DiscoveryClient struct {
  12. client consul.Client
  13. register sd.Registrar
  14. config *api.Config
  15. registration *api.AgentServiceRegistration
  16. }
  17. func NewAgentServiceRegistration(serviceName, instanceId, healthCheckUrl, serviceAddr string, servicePort int, meta map[string]string) *api.AgentServiceRegistration {
  18. return &api.AgentServiceRegistration{
  19. ID: instanceId,
  20. Name: serviceName,
  21. Address: serviceAddr,
  22. Port: servicePort,
  23. Meta: meta,
  24. Check: &api.AgentServiceCheck{
  25. DeregisterCriticalServiceAfter: "30s",
  26. HTTP: "http://" + serviceAddr + ":" + strconv.Itoa(servicePort) + healthCheckUrl,
  27. Interval: "15s",
  28. },
  29. }
  30. }
  31. func NewDiscoveryClient(host string, port int, registration *api.AgentServiceRegistration) (*DiscoveryClient, error) {
  32. config := api.DefaultConfig()
  33. config.Address = host + ":" + strconv.Itoa(port)
  34. client, err := api.NewClient(config)
  35. if err != nil{
  36. return nil, err
  37. }
  38. sdClient := consul.NewClient(client)
  39. return &DiscoveryClient{
  40. client: sdClient,
  41. config: config,
  42. registration: registration,
  43. register: consul.NewRegistrar(sdClient, registration, log.NewLogfmtLogger(os.Stderr)),
  44. }, nil
  45. }
  46. func (consulClient *DiscoveryClient) Register(ctx context.Context) {
  47. consulClient.register.Register()
  48. }
  49. func (consulClient *DiscoveryClient) Deregister(ctx context.Context) {
  50. consulClient.register.Deregister()
  51. }
  52. func (consulClient *DiscoveryClient) DiscoverServices(ctx context.Context, serviceName string) ([] *api.AgentService, error) {
  53. result, _, err := consulClient.client.Service(serviceName, "", false, nil)
  54. if err != nil{
  55. return nil, err
  56. }
  57. rsp := make([]*api.AgentService, 0, len(result))
  58. for _, v := range result{
  59. rsp = append(rsp, v.Service)
  60. }
  61. return rsp, err
  62. }