Статьи

Сборка игры Mancala в микросервисах с использованием Spring Boot (часть 1: Архитектура решения)

Сделайте игру Mancala такой! 

В настоящее время с популярностью микросервисов, когда мы говорим о разработке масштабируемых приложений, мы неизбежно думаем о том, чтобы объединить приложение в микросервисы с высокой степенью разделения, которые можно масштабировать независимо в соответствии с потребностями клиентов, и при этом можно управлять с помощью различных доступных стандартных отраслевых инструментов. такие как Docker-compose, Kubernetes, Istio, Linkerd и др.


Вам также может понравиться:
Микросервисы с Spring Boot, часть 1 — Начало работы

Если вы знакомы с терминами Microservices и хотите погрузиться непосредственно в детали реализации, вы можете пропустить эту часть и прочитать статью Создание игры Mancala в Microservices с использованием Spring Boot (часть 2).

Ниже приведен типичный пример реализации онлайн-игры под названием mancala, которую я разработал с использованием технологий Java , Spring Boot и Spring Cloud на основе подхода Microservices.

Вы можете найти полный источник этой статьи, размещенной в моей учетной записи GitHub  .

Реализация состоит из двух микросервисов, предназначенных для этой игры:

  1. микросервис mancala-api’  : основанная на TDD реализация Mancala Game API с двумя конечными точками.

    • Конечная точка « CreateGame» : для создания новой игры.

    • Конечная точка SowGame’ : для посева определенного индекса ямы в игре.

  2. микросервис mancala-web’  : предоставляет простой пользовательский интерфейс для использования службы API Manacala.

Технологический стек

Технологии, используемые для этой реализации:

  • « Spring Cloud», используется для создания приложений Microservices в Java.

  • Spring MVC’, для создания RESTful API.

  • « Vaadin» , современные компоненты пользовательского интерфейса для создания веб-приложений на Java.

  • « MongoDB» , NoSQL базы данных для сохраняющейся информации игры.

  • « Redis» , Key-Value в памяти структуры данных для кэширования экземпляров игры.

  • « Cassandra» , распределенная база данных NoSQL, используемая в качестве хранилища Zipkin.

  • « Докер» , для контейнеризации услуг.

  • Docker-Compose’ , чтобы связать контейнеры.

  • « Консул» , служба поиска / обнаружения.

  • « Лента» , балансировка нагрузки клиента для вызова службы.

  • « Apache Httpd» , маршрутизация запросов и балансировка нагрузки HTTP.

  • « Кураж» , Кураж-интерфейс для документации API.

  • « Микрометр» , механизм экспорта показателей загрузки по умолчанию.

  • « Актуатор» , мониторинг приложения, сбор метрик, понимание трафика.

  • Весна Облако Сыщик’ , распределенное решение трассировки для Spring Cloud.

  • « Zipkin» , распределенная система отслеживания для отслеживания вызовов службы и визуализации отслеживания.

  • « WireMock» , межсервисное тестирование связи.

  • « Spring Cloud Contract» , Тестирование на основе потребительских контрактов для микросервисов.

Вот общая архитектура решения:

Ниже приведено пошаговое описание решения, обсуждались технологии и способы его дальнейшей настройки в соответствии с вашими интересами.

1— Консульская служба регистрации и обнаружения

Как показано на рисунке выше, наши микросервисы зарегистрированы в реестре сервисов Consul,  и поэтому мы будем использовать API обнаружения сервисов, предоставляемый Spring Cloud , чтобы обнаруживать экземпляры этих микросервисов из реестра Consul, добавляя зависимость ниже к pom клиента. XML

и используя @EnableDiscoveryClient в Spring Boot Application нашего клиента:

@SpringBootApplication
@EnableDiscoveryClient
@RibbonClient("mancala-service")
public class MancalaGameWebApplication {

2 — Apache HTTP Балансировщик нагрузки

Apache HTTP is used to forward HTTP requests to our microservices whose ports are not exposed! Apache HTTP is configured as a reverse proxy for this purpose and as a load balancer i.e. if you start multiple instances of a microservices by below command, Apache will recognize the new instances:

[.\mancal-game\docker] docker-compose scale mancala-api=3

3 — Ribbon Client-Side Load Balancer

Once we have requirements for scaling up our services in a microservice environment using many available tools such as Docker-compose, Kubernetes and etc, there is a need to know how to balance the load between these microservices and make sure that we can configure these invocations based on our requirements. In this application, I have used Netflix Ribbon client-side load balancing to provide solid experience for clients while communicating with other microservices and still maintaining the service-state if we are dealing with Stateful-services.

4 — Zipkin Distributed Tracing With Spring Sleuth

One of the strict requirements within microservices architecture is to have an end-to-end visualization on complex inter-microservice communication scenarios where the requests initiated by the client application possibly span more than one microservices and lead to spawning new messages alongside. As our microservice application evolves, more services added to the system and therefore we need a tool to prob any performance bottlenecks might occur within a specific business transaction or between two services and get runtime information about those events.

Zipkin is an application for visualizing traces between and within services. Spring Cloud Sleuth can be used by microservices developed using Spring Cloud, to simplify both the creation of trace events and sending them to the Zipkin server. Spring Cloud Sleuth intercepts incoming requests and either pick up the trace id from the incoming message or creates a new trace id if none was specified. For outgoing requests, it fills in the current trace id in the outgoing message.

You can enable Zipkin and Spring Sleuth by adding below dependency into your pom.xml file:

<!-- Zipkin -->
<dependency> 
  <groupId>org.springframework.cloud</groupId>   
  <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

In this application, Zipkin dashboard shows trace calls between mancala-web and mancala-API microservices which can be accessed here: http://localhost:9411.

5 — Prometheus

Prometheus is an open-source monitoring system with a dimensional data model, flexible query language, efficient time-series database, and modern alerting approach. In this application, microservices are configured to send metrics to Prometheus server for monitoring which can be seen at http://localhost:9090.

Micrometer is default Spring boot metrics export engine which can be enabled and used to send metrics to Prometheus server by adding below dependencies to your pom.xml file:

<!-- Micormeter core   -->
<dependency>   
  <groupId>io.micrometer</groupId>   
  <artifactId>micrometer-core</artifactId>
</dependency>

<!-- Micrometer Prometheus registry  -->
<dependency>   
  <groupId>io.micrometer</groupId>   
  <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

6 — Grafana Dashboard

Grafana is the leading open-source project for visualizing collected metrics provided by the Prometheus server. You can access to Grafana dashboard at http://localhost:3000.

7 — ELK-Stack

We often need to have access to application logs at runtime for debugging purposes or analyzing the application behavior over certain conditions. The best open source tool for ingesting data from different sources, transforming data to custom formats and finally providing searching functionality on top of them is provided by ELK-Stack which consists of Elasticsearch, Logstash, and Kibana.

In this application, we have configured Filebeat to send logs generated by our Microservices to Logstash which in turn are transferred to the Elastic search server.

You can access to Kibana dashboard at http://localhost:5601.

After you configure the Kibana dashboard, you can search on Logs for any data collected by our application, e.g. ‘PlayerTurn’ to see how ‘playerTurn’ parameter has changed over several mancala-API call to sow() Endpoint.

8 — Build and Run Using Docker-Compose

You can find the complete source for this article hosted on my GitHub repository. A detail instructions are provided here which show you how to build and run the game with three different options. Once you run the server you can access the Game landing page at this address: http://localhost

Before building the game, there is an environment variable called ‘MANCALA_PIT_STONES’ within the docker-compose.yml files for ‘mancala-api’ service which allows you to customize the Mancala game based on the number of stones. The default value for this variable is 6.

9 — Implementation Details

I have provided detail implementation for the above solution in three separate articles:

Your valuable comments and feedbacks are highly appreciated!

Further Reading

Quick Guide to Microservices With Spring Boot 2.0, Eureka, and Spring Cloud

Microservices Architecture With Spring Boot and Spring Cloud

Creating Microservices With Spring and Eureka