Message brokers#

General information#

Сервис брокера сообщений обеспечивает обмен сообщениями между различными приложениями, системами и сервисами в облаке. Он позволяет приложениям взаимодействовать друг с другом посредством асинхронных сообщений, без необходимости постоянного соединения или без знания о взаимном местоположении. В К2 Облаке поддерживаются популярные брокеры сообщений Apache Kafka и RabbitMQ.

Apache Kafka#

Высокопроизводительный и надёжный брокер сообщений Apache Kafka предназначен для обработки больших объёмов данных в режиме реального времени. С его помощью компоненты распределённой системы могут быстро и эффективно обмениваться сообщениями.

Благодаря своей распределённой архитектуре Apache Kafka обладает высокой отказоустойчивостью и эффективен при работе с критически важными приложениями. Он гарантирует доставку сообщений и поддерживает различные модели обработки данных, включая потоковую обработку и обработку пакетов данных. Благодаря этим возможностям Apache Kafka широко используется в различных областях, где требуется быстрый и надёжный обмен большими объёмами данных.

Apache Kafka предлагает гибкую систему топиков и разделов, позволяющую разделить поток сообщений на отдельные потоки и упрощающую обработку данных. Такая структура обеспечивает более высокую пропускную способность и позволяет пользователям масштабировать систему в соответствии с их требованиями. Брокер поддерживает как отдельные сообщения, так и пакеты сообщений, что даёт возможность оптимизировать производительность и эффективность передачи данных.

Система репликации в Apache Kafka обеспечивает защиту от сбоев и потери данных, а такие механизмы, как commit log и consumer offsets, позволяют контролировать процесс обработки сообщений и гарантировать последовательность обработки данных.

Apache Kafka стал стандартом обмена данными в режиме реального времени во многих отраслях и приложениях. Эта мощная и гибкая система обработки сообщений продолжает развиваться и улучшаться, предлагая новые возможности для обработки и анализа больших объёмов данных.

В К2 Облаке поддерживаются следующие версии Apache Kafka:

  • 3.6.1;

  • 3.7.0.

RabbitMQ#

RabbitMQ is a popular open source message broker. It serves as an intermediary in the message transmission between information system components. Thanks to the broker, they no longer need to monitor message delivery status, resend messages or wait for the transmission to complete, since the broker solves all these tasks. Thus, you can improve overall system performance by reducing the number of jobs done by other system components and time spent on their execution.

RabbitMQ offers rich functionality for customizing and optimizing the messaging process according to the system needs. For example, you can use different protocols to send and receive messages, set up routing rules, specify message handling priorities, and more.

Thanks to a lot of messaging protocols supported, RabbitMQ can be used in multi-protocol systems. In particular, it supports AMQP (Advanced Message Queuing Protocol), MQTT (Message Queuing Telemetry Transport), STOMP (Streaming Text Oriented Messaging Protocol), and XMPP (Extensible Messaging and Presence Protocol).

In addition, RabbitMQ features high degree of reliability and availability. Built-in replication and clustering mechanisms allow you to create message-intensive HA systems.

K2 Cloud supports the following RabbitMQ versions:

  • 3.8;

  • 3.9;

  • 3.10.

Before you begin#

To be able to work with the broker service, a user needs to have PaaSServicePolicy project grants. For instance, such grants are available to administrators in CloudAdministrators group. If necessary, you can create a separate user, add the user to the project, and either attach the PaaSServicePolicy policy to the user or add the user to the group of cloud administrators in this project.

In addition, the project should have the following resources:

We also advise to read the recommendations on how to work with the service in the cloud.

Запуск сервиса брокера сообщений#

Для запуска сервиса в подразделе Витрина сервисов или Установленные сервисы выберите сервис на вкладке Брокеры сообщений и нажмите Создать.

The service launch procedure comprises the following stages:

  1. Set the required network parameters:

    • The configuration of the cluster in which the service will be deployed. The following options are available for selection:

      • single-node (non-high-availability service);

      • three notes in one availability zone;

      • с тремя узлами в трёх зонах доступности.

      • с шестью узлами в одной зоне доступности (3 брокера и 3 координатора);

      • с шестью узлами в трёх зонах доступности (3 брокера и 3 координатора);

    • VPC where the service will be deployed.

    • Группы безопасности для регулирования трафика на интерфейсах экземпляров, где будет запущен сервис.

    • Subnets where the message broker service will be deployed, or network interfaces through which cluster nodes will connect to subnets.

    Note

    To run the service in the selected VPC, you must first create a subnet in the preferred availability zone (in a configuration with one zone), or one subnet in each availability zone (in a configuration with three zones). In addition, the same volume types must be supported in the availability zones used.

    Note

    The ability to attach network interfaces may be useful, for example, when you need to recreate the cluster where the message broker has been deployed. If you delete a service, but do not delete attached network interfaces, you will be able to reuse them for connecting nodes of a new cluster to subnets, where the new cluster will be deployed. Thus, you can keep previous network settings, such as private IP addresses and security groups, rather than configure them again.

    • (Только для RabbitMQ) Внутренний и/или внешний балансировщики нагрузки, когда выбрана конфигурация кластера с тремя узлами (см. подробнее Load balancer management).

  2. Set the configuration of one or more instances on which the message broker service will run.

    Выберите конфигурацию экземпляра, на котором будет развёрнут мастер-узел в случае RabbitMQ и брокер в случае Apache Kafka:

    • тип экземпляра;

    • параметры системного диска: тип, размер и IOPS (если это доступно для выбранного типа);

    • параметры диска для данных: тип, размер и IOPS (если это доступно для выбранного типа);

    Для сервиса Apache Kafka необходимо также выбрать конфигурацию экземпляра, на котором будет развёрнут координатор.

    In addition, you can specify an SSH key. In this case, after automatic service configuration, you will have SSH access to the respective instances.

    Attention

    Мы предоставляем возможность подключения к экземплярам виртуальных машин по SSH-ключу, пока сервисы брокера сообщений находятся на этапе бета-тестирования. Данная возможность в будущем может быть отключена.

  3. Set the main service parameters:

    • Service name – any unique name for the caching service.

    • Version.

    • Monitoring agent installation option. For centralized monitoring of a message broker service, deploy the Prometheus-based monitoring service first.

      • Monitoring service – The selection of a monitoring service is only available when the Enable monitoring checkbox is checked.

      • Monitoring labels — Optionally, you can set monitoring labels, which the installed monitoring agents will assign to the collected metrics (for details, see Using labels). Labels can only be set when the Enable monitoring checkbox is selected.

    • Logging agent installation option – For centralized PaaS service logging, first create a logging service. Once a PaaS service is created, you will be able to install logging agents manually only.

      • Logging service – The selection of a logging service is only available when the Enable logging checkbox is checked.

      • Logging tags – Tags are assigned to logs when the latter are imported by the logging service. They simplify search for the required logs. Tags can only be set when the Enable logging checkbox is checked.

    • Пароль пользователя (только для RabbitMQ). Его можно задать вручную или сгенерировать автоматически.

  4. Set the advanced settings, if necessary. Click advanced settings and enter the settings and their values.

    Important

    The specified settings will be a part of the service configuration and, therefore, will affect its operation. Add only the settings you really need.

  5. Click Create.

    Note

    The service launching process usually takes 5 to 15 minutes.

Управление топиками Kafka#

Для сервиса Apache Kafka вы можете создать и настроить топики.

Создание топика#

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. Откройте вкладку Топики и нажмите Создать.

  4. В открывшемся окне задайте следующие обязательные параметры:

    • Имя топика.

    • Количество разделов (не больше, чем брокеров).

    • Количество реплик разделов (не больше, чем брокеров).

  5. Если требуется задать другие параметры, перейдите на следующий шаг, нажав Дополнительные параметры. Список поддерживаемых параметров и их допустимых значений можно посмотреть на странице Параметры топика Kafka.

  6. После задания всех необходимых параметров нажмите Создать.

Редактирование топика#

Если требуется изменить параметры топика, выполните следующие действия:

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. Откройте вкладку Топики, выберите нужный топик в таблице ресурсов нажмите Изменить.

  4. Вы можете изменить следующие параметры топика:

    • Количество разделов (можно только увеличить).

    • Количество реплик разделов.

  5. Если требуется изменить значения других параметров, перейдите на следующий шаг, нажав Дополнительные параметры. Список поддерживаемых параметров и их допустимых значений можно посмотреть на странице Параметры топика Kafka.

  6. После задания всех необходимых параметров нажмите Сохранить.

Удаление топика#

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. Откройте вкладку Топики, выберите нужный топик в таблице ресурсов нажмите Удалить.

  4. In the dialog window, confirm the action.

Load balancer management#

Для сервиса RabbitMQ в отказоустойчивой конфигурации с тремя узлами можно создать внутренний и/или внешний балансировщики нагрузки (подробнее о балансировщиках). Они автоматически распределяют поступающие запросы между узлами кластера.

Load balancers are created automatically; their parameters and associated resources cannot be changed. Information about the created load balancers, in particular their DNS names, can be found in the Load balancers tab on the service page.

Attention

A load balancer running together with a PaaS service can be deleted only on the page of this service.

Important

To run the internet-facing load balancer, give external access to HAProxy ports, which is denied by default. Add enabling rule for tcp/5000 port to the security group that was specified when creating the service.

Create a load balancer#

A load balancer for a message broker service can only be created when the service is in Running status. You can create one internal and one internet-facing load balancer per service.

Important

You can create an internal load balancer only if route propagation is enabled in VPC.

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. Open the Load balancers tab and click Create.

  4. In the window that opens, select a balancer you want to create. If none has been created yet, you can create both internal and internet-facing balancers at once.

  5. Click Create to complete the action.

Delete load balancer#

Load balancer associated with the service can only be deleted when the service is in Running status.

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. Open the Load balancers tab and click Delete.

  4. In the window that opens, select a load balancer you want to delete. If two load balancers have been created for the service, you can delete both at the same time.

  5. Click Delete to confirm the action.

Настройка сервиса брокера сообщений#

If you have not enabled monitoring and/or logging when creating the message broker service, or you want to disable them, you can do it when the service is in the Ready state. You can also change the password and advanced settings.

Note

To enable monitoring and logging, first deploy Prometheus-based monitoring service and ELK-based logging service.

Important

If an attempt to modify some settings fails, then the service will be reset to default ones.

To set up the message broker service:

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. Open the Parameters tab and click Modify.

  4. In the window that opens, you can generate or set a new password and configure monitoring and logging (or disable them if they are already enabled).

  5. To change the advanced settings, click Additional parameters. Then click Advanced settings and set the new settings and their values.

  6. To save settings, click Modify.

Environment upgrade#

Сервисы PaaS регулярно обновляются. Если вы хотите, чтобы уже установленный сервис брокера сообщений поддерживал новые возможности, то обновите его окружение на новую версию. Текущую версию окружения можно узнать на вкладке Информация на странице сервиса.

Note

All services with environment version 3_6 and higher support environment update. It is also available for some previously deployed services with environment version 3_5. To check if you can update them, use the API method DescribeService: the response should contain the common:update_environment value in the SupportedFeatures list.

Important

If an attempt to update the environment fails, the service will be reset to the default one.

To update the environment version:

  1. Go to PaaS Running services and open the Message brokers tab.

  2. Find the desired service in the table and click the service ID to go to its page.

  3. In the Information tab, click Update environment version.

  4. In the window that opens, select the version from the list, to which you want to upgrade the current environment.

  5. Click Update to change the version.

Удаление сервиса брокера сообщений#

Удаление сервиса брокера сообщений предполагает удаление всех созданных вместе с ним экземпляров и дисков.

You can delete the service using one of the following methods.

  1. Go to the section PaaS Running services.

  2. Open the Message brokers tab.

  3. Find the service in the table and click on the icon .

  4. If you want to use network interfaces in the future, for example, to recreate a service on the cluster with the same network parameters, then, in the window that opens, disable the Delete associated network interfaces option.

  5. Confirm the action.

  1. Go to the section PaaS Running services.

  2. Open the Message brokers tab.

  3. Find the service in the table and go to the service page.

  4. Click :Delete in the Information tab.

  5. If you want to use network interfaces in the future, for example, to recreate a service on the cluster with the same network parameters, then, in the window that opens, disable the Delete associated network interfaces option.

  6. Confirm the action.