registry

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2020 License: Apache-2.0 Imports: 8 Imported by: 3

README

Simple Service registry based on pub/sub pattern

License Apache 2

This first version service registry use nats (https://nats.io/) to implement a service registry You just need to start nats before using this service registry

The project is still under development and is not ready for production.

Simple to use:

API is simple to use, simple to understand. No required external installation. No configuration file is required.

  • Connect: registry.Connect(registry.Nats(c)) init the service both on the client/server side and return registry service instance.
  • Register: reg.Register(registry.Service{Name: "httptest", URL: "http://localhost:8083/test"}) register you service on the service side.
  • GetService: reg.GetService("myservice") on the client side
  • Unregister: reg.Unregister("myservice") on the service side
  • Close : reg.Close() on the server side 'Close' function deregisters all registered services. On the client and service side, unsubsribe to subscriptions

Safe

Can be used in concurrent context. Singleton design pattern is used. The first called to registry.Connect(registry.Nats(c), registry.Timeout(100*time.MilliSecond)) create instance of registry service. And then you can get an instance of registry service without argument reg, _ := registry.Connect()

Fast

This "service registry" uses a local cache as well as the pub / sub pattern. The registration of a new service is in real time. When a new service registers, all clients are notified in real time and update their cache.

Light

The project uses very few external dependencies. There is no service to install. Just your favorite pub/sub implementation (NATS)

Multi-tenant

Multi-tenant support is planned. The tool is based on pub / sub, each message can be pre-fixed by a text of your choice.

Exemple

on the server side :

    //connect to nats server
    c, err := nats.Connect("localhost:4222")
    if err != nil {
        log.Fatal("Could not connect to nats: ", err)
    }
    //Create registry instance
    reg, err := registry.Connect(registry.Nats(c))
    if err != nil {
        log.Fatal("Could not open registry session", err)
    }
    //Register
    unregister, err := reg.Register(registry.Service{Name: "httptest", URL: "http://localhost:8083/test"})
    if err != nil {
        log.Fatal("Could not register the service ", err)
    }
    //call the unregister func when the service is shuting done
    defer unregister()
    // Start your service ...
    

On the client side :

    //connect to nats server
    c, err := nats.Connect("localhost:4222")
    if err != nil {
		log.Fatal("Could not connect to nats: ", err)
    }
    //Create registry instance
    reg, err := registry.Connect(registry.Nats(c))
	if err != nil {
		log.Fatal("Could not open registry session", err)
    }
    //registry service register to nats all event for the service httptest
    //This is optional, registry
    err = registry.Observe("httptest")
    if err != nil {
        log.Error("Could not observe service ", err)
        return
    }

    services, err := r.GetServices( "httptest")
    if err != nil {
        log.Error("Could not get services ", err)
        return
    }
    //Do something with services

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//DefaultTimeout timeout for GetServices
	DefaultTimeout = 100 * time.Millisecond
	//DefaultRegisterInterval time between 2 registration
	DefaultRegisterInterval = 20 * time.Second
	//DefaultCheckDueInterval time between 2 checks
	DefaultCheckDueInterval = 200 * time.Millisecond
	//DefaultMainTopic default message base. All topics will start with this message
	DefaultMainTopic = "registry"
	//DefaultDueDurationFactor service expire when currentTime > lastRegisteredTime + registerInternal * dueDrationFactor
	DefaultDueDurationFactor = float32(1.5)
)
View Source
var (
	//ErrNotFound when no service found
	ErrNotFound = errors.New("No service found")
)

Functions

func SetFlags

func SetFlags()

SetFlags set go flags. Call this func if you want to override default parameters with command line argument

Types

type Event added in v0.0.6

type Event string

Event represent event (register|unregister|unavailbale)

const (
	//Register register event
	Register Event = "register"
	//Unregister unregister event
	Unregister Event = "unregister"
)

type Filter

type Filter func(services []*Pong) []*Pong

Filter used for filtering service do not return nil Ex Load Balancing

func LoadBalanceFilter

func LoadBalanceFilter() Filter

LoadBalanceFilter basic loadbalancer

func LocalhostFilter

func LocalhostFilter() Filter

LocalhostFilter return true if hostname is equals to service host

type FnUnregister

type FnUnregister func()

FnUnregister call this func for unregister the service

type ObserveFilter added in v0.0.6

type ObserveFilter func(s *Pong) bool

ObserveFilter used to accept (or not) new registered service.

Ex: you want only service on same host

func LocalhostOFilter added in v0.0.6

func LocalhostOFilter() ObserveFilter

LocalhostOFilter accept only service on the same machine

type ObserverEvent added in v0.0.6

type ObserverEvent func(s Service, ev Event)

ObserverEvent event tigered

type Option

type Option func(opts *Options)

Option option func

func AddFilter

func AddFilter(f Filter) Option

AddFilter add filter

func AddObserveFilter added in v0.0.6

func AddObserveFilter(f ObserveFilter) Option

AddObserveFilter adding filter

func MainTopic

func MainTopic(topic string) Option

MainTopic all topic will start with topic. Usefull in multi-tenancy

func RegisterInterval

func RegisterInterval(duration time.Duration) Option

RegisterInterval time between 2 register publish

func SetObserverEvent added in v0.0.6

func SetObserverEvent(ev ObserverEvent) Option

SetObserverEvent set handler for Observer Event

func Timeout

func Timeout(timeout time.Duration) Option

Timeout define timeout

func WithPubsub added in v0.0.6

func WithPubsub(pb Pubsub) Option

WithPubsub initialyse service registry with nats connection

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options all configurable option

type Pong

type Pong struct {
	Service
	Timestamps *Timestamps `json:"t,omitempty"`
}

Pong response to ping

func (Pong) String

func (p Pong) String() string

type Pubsub added in v0.0.6

type Pubsub interface {
	Sub(topic string, f func(m *PubsubMsg)) (Subscription, error)
	Pub(topic string, data []byte) error
}

Pubsub interface used in registry for pubsub operation

type PubsubMsg added in v0.0.6

type PubsubMsg struct {
	Data    []byte
	Subject string
}

PubsubMsg message for pubsub event

type Registry

type Registry interface {
	Register(s Service) (FnUnregister, error)
	Unregister(s Service) error
	GetServices(name string) ([]Service, error)
	GetService(name string, filters ...Filter) (*Service, error)
	Observe(serviceName string) error
	Close() error
}

Registry Register, Unregister

func Connect

func Connect(opts ...Option) (r Registry, err error)

Connect pubsub transport

type Service

type Service struct {
	//Network tcp/unix/tpc6
	Network string `json:"net,omitempty"`
	//Bind address
	Address string `json:"add,omitempty"`
	//URL base used for communicate with this service
	URL string `json:"url,omitempty"`
	//Name service name
	Name string `json:"name,omitempty"`
	//Version semver version
	Version string `json:"v,omitempty"`
	//Host
	Host string `json:"h,omitempty"`
	// contains filtered or unexported fields
}

Service service struct

func (Service) DueTime

func (s Service) DueTime() time.Time

DueTime expiration time

func (Service) String

func (s Service) String() string

type Subscription added in v0.0.6

type Subscription interface {
	Unsub() error
	Subject() string
}

Subscription subscription

type Timestamps

type Timestamps struct {
	//date registered in nanoseconds (unix timestamp)
	Registered int64
	//expiration duration in milliseconds
	Duration int
}

Timestamps define registered datetime and expiration duration

Directories

Path Synopsis
httptest command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL