Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Микросервисы с go-micro

Микросервисы с go-micro

Iskander (Alex) Sharipov

January 05, 2019
Tweet

More Decks by Iskander (Alex) Sharipov

Other Decks in Programming

Transcript

  1. Micro A platform for microservice development Micro это экосистема и

    платформа для разработки распределенных приложений. Micro позволяет не беспокоится о деталях реализации инфраструктуры и сосредоточится на написании бизнес-логики. https://micro.mu/
  2. go-micro Go Micro is a pluggable framework for micro service

    development. Go Micro позволяет абстрагироваться от деталей реализации распределенных систем. Вот некоторые ключевые возможности фреймворка: • Service Discovery - Автоматическая регистрация сервисов, их поиск и разрешение имен • Load Balancing - Умная балансировка нагрузки между сервисами с использованием различных стратегий • Synchronous Comms - Синхронные RPC коммуникации с возможностью двустороннего стриминга • Asynchronous Comms - PubSub модель, позволяющая реализовать Event-Driven системы • Message Encoding - Кодирование/декодирование сообщений из коробки с использованием json/protobuf • Service Interface - Унифицированный интерфейс высокого уровня для описания и конфигурации сервисов
  3. registry // The registry provides an interface for service discovery

    // and an abstraction over varying implementations // {consul, gossip, etcd, zookeeper, k8s, mdns, memory...} type Registry interface { Init(...Option) error Options() Options Register(*Service, ...RegisterOption) error Deregister(*Service) error GetService(string) ([]*Service, error) ListServices() ([]*Service, error) Watch(...WatchOption) (Watcher, error) String() string } Предоставляет интерфейс для реализации механизма Service Discovery
  4. selector // Selector builds on the registry as a mechanism

    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 } Предоставляет интерфейс для реализации балансировки нагрузки и фильтрации сервисов
  5. transport // Transport is an interface which is used for

    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 } Предоставляет интерфейс использующийся для синхронной коммуникации типа запрос/ответ между сервисами
  6. broker // Broker is an interface used for asynchronous messaging.

    // (HTTP, RabbitMQ, gRPC, Kafka, Redis, NATS, etc…) type Broker interface { Options() Options Address() string Connect() error Disconnect() error Init(...Option) error Publish(string, *Message, ...PublishOption) error Subscribe(string, Handler, ...SubscribeOption) (Subscriber, error) String() string } Предоставляет интерфейс асинхронной коммуникации типа pub/sub
  7. codec // Codec encodes/decodes various types of messages used within

    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 } Используется для кодирования/декодирования сообщение перед передачей
  8. server // Server is a simple micro server abstraction (rpc,

    http, grpc, …) type Server interface { Options() Options Init(...Option) error Handle(Handler) error NewHandler(interface{}, ...HandlerOption) Handler NewSubscriber(string, interface{}, ...SubscriberOption) Subscriber Subscribe(Subscriber) error Register() error Deregister() error Start() error Stop() error String() string } Основной “строительный блок” для написания сервисов
  9. client // Client is the interface used to make requests

    to services. // It supports Request/Response via Transport and Publishing via the Broker. // It also supports bidiectional streaming of requests. (rpc, http, grpc, …) type Client interface { Init(...Option) error Options() Options NewMessage(topic string, msg interface{}, opts ...MessageOption) Message NewRequest(service, method string, req interface{}, reqOpts ...RequestOption) Request Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error Stream(ctx context.Context, req Request, opts ...CallOption) (Stream, error) Publish(ctx context.Context, msg Message, opts ...PublishOption) error String() string } Предоставляет интерфейс для отправки запросов к сервисам
  10. service // Service is an interface that wraps the lower

    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 } Абстракция объединяющая весь функционал фреймворка в один высокоуровневый интерфейс
  11. Пример package main import ( "log" "time" hello "github.com/micro/examples/greeter/srv/proto/hello" "github.com/micro/go-micro"

    "context" ) type Say struct{} func (s *Say) Hello(ctx context.Context, req *hello.Request, rsp *hello.Response) error { log.Print("Received Say.Hello request") rsp.Msg = "Hello " + req.Name return nil } func main() { service := micro.NewService( micro.Name("go.micro.srv.greeter"), micro.RegisterTTL(time.Second*30), micro.RegisterInterval(time.Second*10), ) // optionally setup command line usage service.Init() // Register Handlers hello.RegisterSayHandler(service.Server(), new(Say)) // Run server if err := service.Run(); err != nil { log.Fatal(err) } }
  12. micro Micro is a toolkit for cloud-native development. It helps

    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.
  13. CLI Консольный интерфейс для управления микро-сервисами NAME: micro - A

    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
  14. Plugins Варианты расширения платформы micro •BuiltIn Plugins (https://github.com/micro/go-plugins) •Explore Third-Party

    Repos (https://micro.mu/explore/) •Реализация интерфейсов go-micro (codec, transport, broker, etc.) •Расширение micro toolkit (С помощью интерфейса Plugin)
  15. Plugins usage #1 import ( "github.com/micro/go-micro" "github.com/micro/go-plugins/registry/kubernetes" ) func main()

    { 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), ) }
  16. Plugins usage #2 import ( "github.com/micro/go-micro" _ "github.com/micro/go-plugins/broker/rabbitmq" _ "github.com/micro/go-plugins/registry/kubernetes"

    _ "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
  17. Toolkit Plugins The plugin Create a plugin.go file in the

    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
  18. В завершение •BuiltIn gRPC (https://micro.mu/docs/go-grpc.html) •Go Config (https://micro.mu/docs/go-config.html) •Go API

    (https://micro.mu/docs/go-api.html) •K8S (https://micro.mu/docs/deploy-kubernetes.html) •Examples (https://github.com/micro/examples)