registry

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2025 License: MIT Imports: 14 Imported by: 0

README

Registry

providing basic registry function

supported database

  • etcd

usage

registry

basic registry, provide instance and service management

package main

import (
	"context"
	"fmt"

	"github.com/junqirao/gocomponents/registry"
)

func main() {
	// optional init instance if you want to register to registry
	ins := registry.NewInstance("your_service_name").
		WithAddress("127.0.0.1", 8080). // provide ip address and port for communication
		WithMetaData(map[string]interface{}{"key": "value"}) // metadata
	// config
	cfg := registry.Config{
		Prefix:            "/test-registry/", // prefix store to database
		HeartBeatInterval: 3,                 // healthy check heartbeat interval default 3s
	}

	// Init registry module with config and sync services info from database and build local caches.
	// if *Instance is provided will be register automatically.
	// if context is done, watch loop will stop and local cache won't be updated anymore.
	err := registry.Init(context.Background(), cfg, ins)
	if err != nil {
		// do something
		return
	}

	// get service from thread safe local cache
	service, err := registry.Registry.GetService(context.Background(), "test-service")
	if err != nil {
		// do something
		return
	}
	fmt.Printf("service: %+v\n", service.Instances())

	// get services from thread safe local cache
	services, err := registry.Registry.GetServices(context.Background())
	if err != nil {
		// do something
		return
	}
	for serviceName, s := range services {
		fmt.Printf("services[%s]: %+v\n", serviceName, s.Instances())
	}

	// register event handler, when instance changes will be triggered
	registry.Registry.RegisterEventHandler(func(instance *registry.Instance, e registry.EventType) {
		fmt.Printf("event: %s, instance: %+v\n", e, instance)
	})

	// if you don't deregister and exit application,
	// the registered instance will delete automatically after heart_beat_interval (default 3s) 
	err = registry.Registry.Deregister(context.Background())
	if err != nil {
		panic(err)
		return
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAlreadyRegistered = errors.New("already registered")
	ErrServiceNotFound   = errors.New("service not found")
)

error define

Functions

func Init

func Init(ctx context.Context, db kvdb.Database, ins ...*Instance) (err error)

Init registry module with config and sync services info from database and build local caches. if *Instance is provided will be register automatically. if context is done, watch loop will stop and local cache won't be updated anymore.

func InitWithConfig

func InitWithConfig(ctx context.Context, config *Config, db kvdb.Database, ins ...*Instance) (err error)

Types

type Config

type Config struct {
	Instance          *Instance `json:"instance"`
	Name              string    `json:"name"`
	HeartBeatInterval int64     `json:"heart_beat_interval"` // default 10s
	MaximumRetry      int       `json:"maximum_retry"`       // default 20
}

Config for registry

type EventHandler

type EventHandler func(i *Instance, e EventType)

EventHandler of instance change

type EventType

type EventType = kvdb.EventType

EventType of instance change, alias of kvdb.EventType

type Instance

type Instance struct {
	Id          string                 `json:"id"`           // uuid
	Host        string                 `json:"host"`         // host
	HostName    string                 `json:"host_name"`    // host name
	Port        int                    `json:"port"`         // port
	ServiceName string                 `json:"service_name"` // service name, usually use it as routing key
	Meta        map[string]interface{} `json:"meta"`         // meta data
}

Instance of registry object

func Current

func Current() *Instance

Current returns copy of current instance, if not registered return Empty Instance

func NewInstance

func NewInstance(serviceName ...string) *Instance

func (*Instance) Clone

func (i *Instance) Clone() *Instance

func (*Instance) Identity

func (i *Instance) Identity(separator ...string) string

Identity generate identity

func (*Instance) String

func (i *Instance) String() string

String of instance

func (*Instance) WithAddress

func (i *Instance) WithAddress(host string, port int) *Instance

func (*Instance) WithMetaData

func (i *Instance) WithMetaData(meta map[string]interface{}) *Instance

type Interface

type Interface interface {

	// Deregister deregister currentInstance
	Deregister(ctx context.Context) (err error)
	// GetService by service name
	GetService(ctx context.Context, serviceName ...string) (service *Service, err error)
	// GetServices of all
	GetServices(ctx context.Context) (services map[string]*Service, err error)
	// RegisterEventHandler register event handler
	RegisterEventHandler(handler EventHandler)
	// contains filtered or unexported methods
}

Interface abstracts registry

var (
	// Registry Global instance of registry, use it after Init
	Registry Interface

	Empty = new(Instance)
)

global variable define

type Service

type Service struct {
	Name string
	// contains filtered or unexported fields
}

Service contains instances

func (*Service) Instances

func (s *Service) Instances() []*Instance

Instances slice copy of this service

func (*Service) Len

func (s *Service) Len() int

Len of instance

func (*Service) Range

func (s *Service) Range(h func(instance *Instance) bool)

Range instances

Jump to

Keyboard shortcuts

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