micro/registry/consul_registry.go

128 lines
2.3 KiB
Go
Raw Normal View History

2015-01-14 02:31:27 +03:00
package registry
import (
"errors"
2015-02-15 02:00:47 +03:00
"sync"
2015-01-14 02:31:27 +03:00
consul "github.com/hashicorp/consul/api"
2015-01-14 02:31:27 +03:00
)
type ConsulRegistry struct {
2015-02-15 02:00:47 +03:00
Address string
Client *consul.Client
2015-01-14 02:31:27 +03:00
2015-02-15 02:00:47 +03:00
mtx sync.RWMutex
services map[string]Service
}
2015-01-14 02:31:27 +03:00
func (c *ConsulRegistry) Deregister(s Service) error {
if len(s.Nodes()) == 0 {
return errors.New("Require at least one node")
}
node := s.Nodes()[0]
_, err := c.Client.Catalog().Deregister(&consul.CatalogDeregistration{
Node: node.Id(),
Address: node.Address(),
ServiceID: node.Id(),
}, nil)
return err
}
func (c *ConsulRegistry) Register(s Service) error {
if len(s.Nodes()) == 0 {
return errors.New("Require at least one node")
}
node := s.Nodes()[0]
_, err := c.Client.Catalog().Register(&consul.CatalogRegistration{
Node: node.Id(),
Address: node.Address(),
Service: &consul.AgentService{
ID: node.Id(),
Service: s.Name(),
Port: node.Port(),
},
}, nil)
return err
}
func (c *ConsulRegistry) GetService(name string) (Service, error) {
2015-02-15 02:00:47 +03:00
c.mtx.RLock()
service, ok := c.services[name]
c.mtx.RUnlock()
if ok {
return service, nil
}
2015-01-14 02:31:27 +03:00
rsp, _, err := c.Client.Catalog().Service(name, "", nil)
if err != nil {
return nil, err
}
cs := &ConsulService{}
for _, s := range rsp {
if s.ServiceName != name {
continue
}
cs.ServiceName = s.ServiceName
cs.ServiceNodes = append(cs.ServiceNodes, &ConsulNode{
Node: s.Node,
NodeId: s.ServiceID,
NodeAddress: s.Address,
NodePort: s.ServicePort,
})
}
return cs, nil
}
func (c *ConsulRegistry) NewService(name string, nodes ...Node) Service {
var snodes []*ConsulNode
for _, node := range nodes {
if n, ok := node.(*ConsulNode); ok {
snodes = append(snodes, n)
}
}
return &ConsulService{
ServiceName: name,
ServiceNodes: snodes,
}
}
func (c *ConsulRegistry) NewNode(id, address string, port int) Node {
return &ConsulNode{
Node: id,
NodeId: id,
NodeAddress: address,
NodePort: port,
}
}
2015-02-15 02:00:47 +03:00
func (c *ConsulRegistry) Watch() {
NewConsulWatcher(c)
}
2015-01-14 02:31:27 +03:00
func NewConsulRegistry() Registry {
2015-02-15 02:00:47 +03:00
config := consul.DefaultConfig()
client, _ := consul.NewClient(config)
2015-01-14 02:31:27 +03:00
2015-02-15 02:00:47 +03:00
cr := &ConsulRegistry{
Address: config.Address,
Client: client,
services: make(map[string]Service),
2015-01-14 02:31:27 +03:00
}
2015-02-15 02:00:47 +03:00
cr.Watch()
return cr
2015-01-14 02:31:27 +03:00
}