платформа для разработки распределенных приложений. Micro позволяет не беспокоится о деталях реализации инфраструктуры и сосредоточится на написании бизнес-логики. https://micro.mu/
development. Go Micro позволяет абстрагироваться от деталей реализации распределенных систем. Вот некоторые ключевые возможности фреймворка: • Service Discovery - Автоматическая регистрация сервисов, их поиск и разрешение имен • Load Balancing - Умная балансировка нагрузки между сервисами с использованием различных стратегий • Synchronous Comms - Синхронные RPC коммуникации с возможностью двустороннего стриминга • Asynchronous Comms - PubSub модель, позволяющая реализовать Event-Driven системы • Message Encoding - Кодирование/декодирование сообщений из коробки с использованием json/protobuf • Service Interface - Унифицированный интерфейс высокого уровня для описания и конфигурации сервисов
to pick nodes // and mark their status. This allows host pools and other things // to be built using various algorithms. (label, blacklist, cache, static…) type Selector interface { Init(opts ...Option) error Options() Options Select(service string, opts ...SelectOption) (Next, error) Mark(service string, node *registry.Node, err error) Reset(service string) Close() error String() string } Предоставляет интерфейс для реализации балансировки нагрузки и фильтрации сервисов
communication between // services. It uses socket send/recv semantics and had various // implementations {HTTP, RabbitMQ, NATS, ...} type Transport interface { Init(...Option) error Options() Options Dial(addr string, opts ...DialOption) (Client, error) Listen(addr string, opts ...ListenOption) (Listener, error) String() string } Предоставляет интерфейс использующийся для синхронной коммуникации типа запрос/ответ между сервисами
go-micro. // ReadHeader and ReadBody are called in pairs to read requests/responses // from the connection. Close is called when finished with the // connection. ReadBody may be called with a nil argument to force the // body to be read and discarded. (json-rpc, proto-rpc, grpc, etc…) type Codec interface { ReadHeader(*Message, MessageType) error ReadBody(interface{}) error Write(*Message, interface{}) error Close() error String() string } Используется для кодирования/декодирования сообщение перед передачей
level libraries // within go-micro. Its a convenience method for building // and initialising services. type Service interface { Init(...Option) Options() Options Client() client.Client Server() server.Server Run() error String() string } Абстракция объединяющая весь функционал фреймворка в один высокоуровневый интерфейс
you build future-proof application platforms and services. The toolkit is composed of the following features: • API Gateway: A single entry point with dynamic request routing using service discovery. • Slack bot: A bot which runs on your platform and lets you manage your applications from Slack itself. • Command line interface: A CLI to describe, query and interact directly with your platform and services from the terminal. • Service templates: Generate new service templates to get started quickly. • Web Dashboard: The web dashboard allows you to explore your services, describe their endpoints, the request and response formats and even query them directly.
cloud-native toolkit USAGE: micro [global options] command [command options] [arguments...] VERSION: 0.8.0 COMMANDS: api Run the micro API bot Run the micro bot registry Query registry call Call a service or function queryDeprecated: Use call instead stream Create a service or function stream health Query the health of a service statsQuery the stats of a service list List items in registry register Register an item in the registry deregister Deregister an item in the registry get Get item from registry proxyRun the micro proxy new Create a new micro service by specifying a directory path relative to your $GOPATH web Run the micro web app
{ registry := kubernetes.NewRegistry() //a default to using env vars for master API service := micro.NewService( // Set service name micro.Name("my.service"), // Set service registry micro.Registry(registry), ) }
_ "github.com/micro/go-plugins/transport/nats" ) func main() { service := micro.NewService( // Set service name micro.Name("my.service"), ) // Parse CLI flags service.Init() } go run service.go --broker=rabbitmq --registry=kubernetes --transport=nats
top level dir package main import ( "log" "github.com/micro/cli" "github.com/micro/micro/plugin" ) func init() { plugin.Register(plugin.NewPlugin( plugin.WithName("example"), plugin.WithFlag(cli.StringFlag{ Name: "example_flag", Usage: "This is an example plugin flag", EnvVar: "EXAMPLE_FLAG", Value: "avalue", }), plugin.WithInit(func(ctx *cli.Context) error { log.Println("Got value for example_flag", ctx.String("example_flag")) return nil }), )) } Building the code Simply build micro with the plugin go build -o micro ./main.go ./plugin.go