Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

Давайте знакомиться Антон Кучеров https://idexter.ru/

Slide 3

Slide 3 text

Ближе к делу…

Slide 4

Slide 4 text

Монолит и микросервисы Монолит Микросервисы

Slide 5

Slide 5 text

Micro A platform for microservice development Micro это экосистема и платформа для разработки распределенных приложений. Micro позволяет не беспокоится о деталях реализации инфраструктуры и сосредоточится на написании бизнес-логики. https://micro.mu/

Slide 6

Slide 6 text

Platform • Framework (https://github.com/micro/go-micro) • Toolkit (https://github.com/micro/micro) • Plugins (https://github.com/micro/go-plugins)

Slide 7

Slide 7 text

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 - Унифицированный интерфейс высокого уровня для описания и конфигурации сервисов

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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 } Предоставляет интерфейс для реализации балансировки нагрузки и фильтрации сервисов

Slide 10

Slide 10 text

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 } Предоставляет интерфейс использующийся для синхронной коммуникации типа запрос/ответ между сервисами

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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 } Используется для кодирования/декодирования сообщение перед передачей

Slide 13

Slide 13 text

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 } Основной “строительный блок” для написания сервисов

Slide 14

Slide 14 text

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 } Предоставляет интерфейс для отправки запросов к сервисам

Slide 15

Slide 15 text

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 } Абстракция объединяющая весь функционал фреймворка в один высокоуровневый интерфейс

Slide 16

Slide 16 text

Пример 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) } }

Slide 17

Slide 17 text

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.

Slide 18

Slide 18 text

API Gateway Паттерн предоставляющий единую точку входа для клиентов и frontend приложений

Slide 19

Slide 19 text

Web Dashboard Предоставляет Web интерфейс для управления, поиска и документации сервисов

Slide 20

Slide 20 text

ChatOps Предоставляет chatops интерфейс для управления микросервисами

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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)

Slide 23

Slide 23 text

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), ) }

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

В завершение •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)

Slide 27

Slide 27 text

На этом у меня все Вопросы?