Перейти к содержимому

Bootstrap yml что это

  • автор:

Spring Configuration Bootstrap и свойства приложения

Spring Boot — это самоуверенная структура. Несмотря на это, обычно мы переопределяем автоматически настроенные свойства в файле конфигурации приложения, таком как application.properties .

Однако в приложении Spring Cloud мы часто используем другой файл конфигурации с именем bootstrap.properties .

В этом кратком руководстве мы объясним различия между bootstrap.properties и application.properties .

2. Когда используется файл конфигурации приложения?​

Мы используем application.yml или application.properties для настройки контекста приложения .

Когда приложение Spring Boot запускается, оно создает контекст приложения, который не нужно настраивать явно — он уже настроен автоматически. Однако Spring Boot предлагает различные способы переопределения этих свойств .

Мы можем переопределить их в коде, аргументах командной строки, параметрах инициализации ServletConfig , параметрах инициализации ServletContext , системных свойствах Java, переменных операционной системы и файле свойств приложения.

Важно помнить, что эти файлы свойств приложения имеют самый низкий приоритет по сравнению с другими формами переопределения свойств контекста приложения.

Мы склонны группировать свойства, которые мы можем переопределить в контексте приложения:

  • Основные свойства (свойства регистрации, свойства потока)
  • Свойства интеграции (свойства RabbitMQ , свойства ActiveMQ )
  • Веб-свойства (свойства HTTP , свойства MVC )
  • Свойства безопасности (свойства LDAP , свойства OAuth2 )

3. Когда используется файл конфигурации Bootstrap?​

Мы используем bootstrap.yml или bootstrap.properties для настройки контекста начальной загрузки . Таким образом, мы сохраняем внешнюю конфигурацию для начальной загрузки и основного контекста четко разделенными.

Контекст начальной загрузки отвечает за загрузку свойств конфигурации из внешних источников и за расшифровку свойств в локальных внешних файлах конфигурации.

Когда приложение Spring Cloud запускается, оно создает контекст начальной загрузки . Первое, что нужно помнить, это то, что контекст начальной загрузки является родительским контекстом для основного приложения.

Еще один важный момент, о котором следует помнить, заключается в том, что эти два контекста совместно используют среду Environment , которая является источником внешних свойств для любого приложения Spring . В отличие от контекста приложения, контекст начальной загрузки использует другое соглашение для поиска внешней конфигурации.

Источником файлов конфигурации может быть, например, файловая система или даже репозиторий git. Службы используют свою зависимость spring-cloud-config-client для доступа к серверу конфигурации.

Проще говоря, сервер конфигурации — это точка, через которую мы получаем доступ к файлам конфигурации контекста приложения .

4. Быстрый пример​

В этом примере файл конфигурации контекста начальной загрузки настраивает зависимость spring-cloud-config-client для загрузки нужных файлов свойств приложения.

Давайте посмотрим на пример файла bootstrap.properties :

spring.application.name=config-client spring.profiles.active=development spring.cloud.config.uri=http://localhost:8888 spring.cloud.config.username=root spring.cloud.config.password=s3cr3t spring.cloud.config.fail-fast=true management.security.enabled=false 

5. Вывод​

В отличие от приложения Spring Boot, приложение Spring Cloud имеет контекст начальной загрузки, который является родителем контекста приложения. Хотя оба они используют одну и ту же среду Environment , у них разные соглашения о расположении внешних файлов конфигурации.

Контекст начальной загрузки ищет файл bootstrap.properties или bootstrap.yaml, тогда как контекст приложения ищет файл application.properties или application.yaml . «

И, конечно же, свойства конфигурации контекста начальной загрузки загружаются до свойств конфигурации контекста приложения.

  • 1. Обзор
  • 2. Когда используется файл конфигурации приложения?
  • 3. Когда используется файл конфигурации Bootstrap?
  • 4. Быстрый пример
  • 5. Вывод

Как я запускал Spring Cloud

Меня зовут Аксёнов Вячеслав, я старший бэкенд Java/Kotlin разработчик в крупном энтерпрайзе. Однажды я попал на проект, полный микросервисов, в котором за конфигурацию отвечала такая штука как Spring Cloud. Чтобы разобраться как именно это работает я исследовал и прикрутил этот диковенный элемент к одному своему пет проекту. И в этой статье я пошагово покажу как я это сделал. А если точнее — как настроить Spring Cloud сервер конфигурации.

Немного вводных данных

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

Для бэкеда крупных систем прямо сейчас в преимуществе используется Java/Kotlin в качестве основного языка программирования. А там где есть Java и энтрпрайз, там рука об руку идет Spring Framework. И так как строить монолиты сейчас не модно, выбор делается в сторону микросервисов. (мое мнение, что делать микросервисы совсем уж микро не стоит. Каждый сервис должен отвечать отдельной бизнес задаче. Но об этом я напишу в отдельной статье) И вот есть зоопарк сервисов — у каждого есть свои конфиги. И их нужно как-то менеджить. Вопрос — как это сделать?

Итак, какую проблему решает Spring Cloud? Представим, что у вас есть 5 приложений на Java/Spring, каждое при старте подгружает разные конфиги (пароли/адреса для базы, внешних апи и тд). Есть разные окружения — test, dev, prod, stage и тд. Spring Cloud позволяет хранить все конфигурации для разных приложений и разных окружений в одном месте.

Как же запускать?

Давайте разбираться как запускать эту систему на простом примере.

Есть несложное приложение на Spring, которое нужно научить ходить в клауд за конфигами. В моем случае этим является бот для логирования рабочего времени в телеграме, который я написал для личных целей — whid (what have I done). Но код открытый — кому интересно можете пользоваться моим, либо запустить для себя. На бизнес логику можно не обращать внимания, нас интересует только конфигурация для работы с Spring Cloud.

Настройка стороны сервиса:

Для этого в список зависимостей нужно добавить spring-cloud-starter-config и spring-cloud-starter-bootstrap:

 org.springframework.cloud spring-cloud-starter-config 3.0.5  org.springframework.cloud spring-cloud-starter-bootstrap 3.0.4 

Версии зависимостей можно брать актуальные с https://search.maven.org/

Также application.properties заменяется на bootstrap.yml, в которой нужно указать название текущего приложения и адрес для подключения к спринг клауду.

spring: application: name: whid-bot config: import: http://localhost:8888/

В данном случае название приложения whid-bot, а адрес для клауда http://localhost:8888/

Этого достаточно — стартеры для spring-cloud уже включают в себя нужные настройки, которые позволят сервису при запуске правильно понять, что используется spring cloud и правильно сходить к нему по настройкам, используемым в bootstrap.yml.

Настройка на стороне spring cloud:

Сам сервис конфигурации является отдельным спринг бут приложением. Для построения такого приложения требуются зависимость spring-cloud-config-server:

 org.springframework.cloud spring-cloud-config-server 3.0.5 

А также остальные зависимости, которые потребуются для работы spring boot приложения, как пример мой pom.xml: https://github.com/v-aksenov/spring-cloud-public/blob/master/pom.xml

Самое интересное начинается в конфигурации этого приложения.

spring.application.name=spring-cloud-name server.port=8888 spring.cloud.config.server.git.uri=https://github.com/user/repo.git spring.cloud.config.server.git.username=git_user spring.cloud.config.server.git.password=******* spring.cloud.config.server.git.searchPaths=

Что значит каждый параметр по порядку:

server.port=8888 — указывает порт, на котором будет запущен клауд. Если не конкретизироваться, то поднимется на дефолтном спринговом 8080

spring.cloud.config.server.git.uri=https://github.com/user/repo.git — так как клауд удобнее всего использовать с конфигами, хранящимися в гите, то конечно ссылка на репозиторий с вашими конфигами, может быть как github, так gitlab, stash и тд.

spring.cloud.config.server.git.username , spring.cloud.config.server.git.password=password — соответственно логин и пароль для подключения к репозиторию с конфигами.

spring.cloud.config.server.git.searchPaths= — это указатель того, что для поиска параметров будет использоваться значение из spring.application.name у приложения, которое обращается к клауду.

Стоит держать в голове, что для разных профилей конфигурации нужно хранить в разных файлах. Например для профиля test — whid-bot-test.yml — для тестового окружения и для профиля prod — whid-bot-prod.yml для продового.

Примеры файлов конфигурации

Внутри моего приватного репозитория, где я храню конфиги для своих пет проектов лежит файлик с конфигурацией моего бота. Файл хранит в себе ровно то, что вы бы хранили в application.properties внутри основного приложения.

bot: username: whiddy_bot token: ******* active: true spring: datasource: url: jdbc:h2:file:./h2-data/whid-bot username: ******* password: ******* driverClassName: org.h2.Driver jpa: spring.jpa.database-platform: org.hibernate.dialect.H2Dialect hibernate.ddl-auto: update h2: console: enabled: true path: /h2-console logging: level: root: INFO file: name: ./logs/whid-bot-logs.log

Итог

Всего вышеописанного достаточно для того, чтобы запустить собственный сервис конфигурации spring cloud и настроить ваш сервис для хождения за конфигами в него. Эта статья была написана как для тех, кто только разбирается с разными элементами инфраструктуры, которые позволяет наворотить Spring Framework, а также для лично меня, который сейчас разобрался в теме и в будущем обязательно забудет, но сможет посмотреть здесь.

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

Всем чистого кода и хорошего дня 🙂

1. Spring Cloud Context: Application Context Services

Spring Boot has an opinionated view of how to build an application with Spring. For instance, it has conventional locations for common configuration files and has endpoints for common management and monitoring tasks. Spring Cloud builds on top of that and adds a few features that probably all components in a system would use or occasionally need.

1.1 The Bootstrap Application Context

A Spring Cloud application operates by creating a “ bootstrap ” context, which is a parent context for the main application. It is responsible for loading configuration properties from the external sources and for decrypting properties in the local external configuration files. The two contexts share an Environment , which is the source of external properties for any Spring application. By default, bootstrap properties (not bootstrap.properties but properties that are loaded during the bootstrap phase) are added with high precedence, so they cannot be overridden by local configuration.

The bootstrap context uses a different convention for locating external configuration than the main application context. Instead of application.yml (or .properties ), you can use bootstrap.yml , keeping the external configuration for bootstrap and main context nicely separate. The following listing shows an example:

bootstrap.yml.

spring: application: name: foo cloud: config: uri: $

If your application needs any application-specific configuration from the server, it is a good idea to set the spring.application.name (in bootstrap.yml or application.yml ).

You can disable the bootstrap process completely by setting spring.cloud.bootstrap.enabled=false (for example, in system properties).

1.2 Application Context Hierarchies

If you build an application context from SpringApplication or SpringApplicationBuilder , then the Bootstrap context is added as a parent to that context. It is a feature of Spring that child contexts inherit property sources and profiles from their parent, so the “ main ” application context contains additional property sources, compared to building the same context without Spring Cloud Config. The additional property sources are:

  • “ bootstrap ” : If any PropertySourceLocators are found in the Bootstrap context and if they have non-empty properties, an optional CompositePropertySource appears with high priority. An example would be properties from the Spring Cloud Config Server. See “ Section 1.6, “Customizing the Bootstrap Property Sources” ” for instructions on how to customize the contents of this property source.
  • “ applicationConfig: [classpath:bootstrap.yml] ” (and related files if Spring profiles are active): If you have a bootstrap.yml (or .properties ), those properties are used to configure the Bootstrap context. Then they get added to the child context when its parent is set. They have lower precedence than the application.yml (or .properties ) and any other property sources that are added to the child as a normal part of the process of creating a Spring Boot application. See “ Section 1.3, “Changing the Location of Bootstrap Properties” ” for instructions on how to customize the contents of these property sources.

Because of the ordering rules of property sources, the “ bootstrap ” entries take precedence. However, note that these do not contain any data from bootstrap.yml , which has very low precedence but can be used to set defaults.

You can extend the context hierarchy by setting the parent context of any ApplicationContext you create — for example, by using its own interface or with the SpringApplicationBuilder convenience methods ( parent() , child() and sibling() ). The bootstrap context is the parent of the most senior ancestor that you create yourself. Every context in the hierarchy has its own “ bootstrap ” (possibly empty) property source to avoid promoting values inadvertently from parents down to their descendants. If there is a Config Server, every context in the hierarchy can also (in principle) have a different spring.application.name and, hence, a different remote property source. Normal Spring application context behavior rules apply to property resolution: properties from a child context override those in the parent, by name and also by property source name. (If the child has a property source with the same name as the parent, the value from the parent is not included in the child).

Note that the SpringApplicationBuilder lets you share an Environment amongst the whole hierarchy, but that is not the default. Thus, sibling contexts, in particular, do not need to have the same profiles or property sources, even though they may share common values with their parent.

1.3 Changing the Location of Bootstrap Properties

The bootstrap.yml (or .properties ) location can be specified by setting spring.cloud.bootstrap.name (default: bootstrap ) or spring.cloud.bootstrap.location (default: empty) — for example, in System properties. Those properties behave like the spring.config.* variants with the same name. In fact, they are used to set up the bootstrap ApplicationContext by setting those properties in its Environment . If there is an active profile (from spring.profiles.active or through the Environment API in the context you are building), properties in that profile get loaded as well, the same as in a regular Spring Boot app — for example, from bootstrap-development.properties for a development profile.

1.4 Overriding the Values of Remote Properties

The property sources that are added to your application by the bootstrap context are often “ remote ” (from example, from Spring Cloud Config Server). By default, they cannot be overridden locally. If you want to let your applications override the remote properties with their own System properties or config files, the remote property source has to grant it permission by setting spring.cloud.config.allowOverride=true (it does not work to set this locally). Once that flag is set, two finer-grained settings control the location of the remote properties in relation to system properties and the application’s local configuration:

  • spring.cloud.config.overrideNone=true : Override from any local property source.
  • spring.cloud.config.overrideSystemProperties=false : Only system properties, command line arguments, and environment variables (but not the local config files) should override the remote settings.

1.5 Customizing the Bootstrap Configuration

The bootstrap context can be set to do anything you like by adding entries to /META-INF/spring.factories under a key named org.springframework.cloud.bootstrap.BootstrapConfiguration . This holds a comma-separated list of Spring @Configuration classes that are used to create the context. Any beans that you want to be available to the main application context for autowiring can be created here. There is a special contract for @Beans of type ApplicationContextInitializer . If you want to control the startup sequence, classes can be marked with an @Order annotation (the default order is last ).

When adding custom BootstrapConfiguration , be careful that the classes you add are not @ComponentScanned by mistake into your “ main ” application context, where they might not be needed. Use a separate package name for boot configuration classes and make sure that name is not already covered by your @ComponentScan or @SpringBootApplication annotated configuration classes.

The bootstrap process ends by injecting initializers into the main SpringApplication instance (which is the normal Spring Boot startup sequence, whether it is running as a standalone application or deployed in an application server). First, a bootstrap context is created from the classes found in spring.factories . Then, all @Beans of type ApplicationContextInitializer are added to the main SpringApplication before it is started.

1.6 Customizing the Bootstrap Property Sources

The default property source for external configuration added by the bootstrap process is the Spring Cloud Config Server, but you can add additional sources by adding beans of type PropertySourceLocator to the bootstrap context (through spring.factories ). For instance, you can insert additional properties from a different server or from a database.

As an example, consider the following custom locator:

@Configuration public class CustomPropertySourceLocator implements PropertySourceLocator < @Override public PropertySource locate(Environment environment) < return new MapPropertySource("customProperty", Collections.singletonMap("property.from.sample.custom.source", "worked as intended")); > >

The Environment that is passed in is the one for the ApplicationContext about to be created — in other words, the one for which we supply additional property sources for. It already has its normal Spring Boot-provided property sources, so you can use those to locate a property source specific to this Environment (for example, by keying it on spring.application.name , as is done in the default Spring Cloud Config Server property source locator).

If you create a jar with this class in it and then add a META-INF/spring.factories containing the following, the customProperty PropertySource appears in any application that includes that jar on its classpath:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

1.7 Logging Configuration

If you are going to use Spring Boot to configure log settings than you should place this configuration in `bootstrap.[yml | properties] if you would like it to apply to all events.

For Spring Cloud to initialize logging configuration properly you cannot use a custom prefix. For example, using custom.loggin.logpath will not be recognized by Spring Cloud when initializing the logging system.

1.8 Environment Changes

The application listens for an EnvironmentChangeEvent and reacts to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way). When an EnvironmentChangeEvent is observed, it has a list of key values that have changed, and the application uses those to:

  • Re-bind any @ConfigurationProperties beans in the context
  • Set the logger levels for any properties in logging.level.*

Note that the Config Client does not, by default, poll for changes in the Environment . Generally, we would not recommend that approach for detecting changes (although you could set it up with a @Scheduled annotation). If you have a scaled-out client application, it is better to broadcast the EnvironmentChangeEvent to all the instances instead of having them polling for changes (for example, by using the Spring Cloud Bus).

The EnvironmentChangeEvent covers a large class of refresh use cases, as long as you can actually make a change to the Environment and publish the event. Note that those APIs are public and part of core Spring). You can verify that the changes are bound to @ConfigurationProperties beans by visiting the /configprops endpoint (a normal Spring Boot Actuator feature). For instance, a DataSource can have its maxPoolSize changed at runtime (the default DataSource created by Spring Boot is an @ConfigurationProperties bean) and grow capacity dynamically. Re-binding @ConfigurationProperties does not cover another large class of use cases, where you need more control over the refresh and where you need a change to be atomic over the whole ApplicationContext . To address those concerns, we have @RefreshScope .

1.9 Refresh Scope

When there is a configuration change, a Spring @Bean that is marked as @RefreshScope gets special treatment. This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance, if a DataSource has open connections when the database URL is changed via the Environment , you probably want the holders of those connections to be able to complete what they are doing. Then, the next time something borrows a connection from the pool, it gets one with the new URL.

Sometimes, it might even be mandatory to apply the @RefreshScope annotation on some beans which can be only initialized once. If a bean is «immutable», you will have to either annotate the bean with @RefreshScope or specify the classname under the property key spring.cloud.refresh.extra-refreshable .

If you create a DataSource bean yourself and the implementation is a HikariDataSource , return the most specific type, in this case HikariDataSource . Otherwise, you will need to set spring.cloud.refresh.extra-refreshable=javax.sql.DataSource .

Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you must invalidate its cache entry.

The RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. The /refresh endpoint exposes this functionality (over HTTP or JMX). To refresh an individual bean by name, there is also a refresh(String) method.

To expose the /refresh endpoint, you need to add following configuration to your application:

management: endpoints: web: exposure: include: refresh

@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behavior. For example, it does not mean that all the @Beans defined in that class are themselves in @RefreshScope . Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope . In that case, it is rebuilt on a refresh and its dependencies are re-injected. At that point, they are re-initialized from the refreshed @Configuration ).

1.10 Encryption and Decryption

Spring Cloud has an Environment pre-processor for decrypting property values locally. It follows the same rules as the Config Server and has the same external configuration through encrypt.* . Thus, you can use encrypted values in the form of * and, as long as there is a valid key, they are decrypted before the main application context gets the Environment settings. To use the encryption features in an application, you need to include Spring Security RSA in your classpath (Maven co-ordinates: «org.springframework.security:spring-security-rsa»), and you also need the full strength JCE extensions in your JVM.

If you get an exception due to «Illegal key size» and you use Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:

Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.

1.11 Endpoints

For a Spring Boot Actuator application, some additional management endpoints are available. You can use:

  • POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels.
  • /actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans.
  • /actuator/restart to close the ApplicationContext and restart it (disabled by default).
  • /actuator/pause and /actuator/resume for calling the Lifecycle methods ( stop() and start() on the ApplicationContext ).

If you disable the /actuator/restart endpoint then the /actuator/pause and /actuator/resume endpoints will also be disabled since they are just a special case of /actuator/restart .

Prev Next
Home 2. Spring Cloud Commons: Common Abstractions

Кастомное автоматическое обновление конфигураций клиентов Spring Cloud Config Server. Часть 1: настройка клиента

Рассмотрим техническое задание, которое включает в себя три основных пункта:

  1. настроить базовое автообновление конфигураций клиентов Spring Cloud Config Server.
  2. на сервере настроить принудительное обновление конфигураций клиентов, если состав хранимой на сервере конфигурации изменится каким-либо образом.
  3. при этом запрещается использовать технологию Spring Cloud Bus и связанную с ней передачу команд на обновление через Kafka или RabbitMQ.

Если вас удивил пункт 3 этого ТЗ, то вы не одиноки — меня он тоже очень удивил. Но это был реальный заказчик, очень негибкий, требовательный к условиям ТЗ и не склонный к переговорам. Учитывая степень его платежеспособности, спорить не хотелось, и иные варианты даже не обсуждались — словом, любой каприз за ваши деньги.

Если у вас нет таких нестандартных требований, вы можете сразу перейти к прекрасному руководству, которое уже публиковалось в блоге компании OTUS. Там есть практически все. Мы же настроим обновление именно для этого нестандартного случая, не слишком углубляясь в стандартные детали, и наоборот, более подробно описав специфические для этого ТЗ особенности настройки.

Итак, у нас есть клиент, обновлять его мы будем, используя возможности Spring Actuator, его использовать не запрещалось, тем более, что он может выполнять и прямые свои обязанности — сбор метрик, что также было нужно в проекте, как бывает и во многих других проектах. Чтобы это заработало, добавим в pom.xml проекта на Maven следующие зависимости:

  org.springframework.boot spring-boot-starter-security  org.springframework.boot spring-boot-starter-actuator  org.springframework.cloud spring-cloud-starter-config  org.springframework.cloud spring-cloud-starter-bootstrap  

Здесь все понятно — защита Spring Boot приложения, сам Actuator, две зависимости для Spring Cloud Server клиента.

В клиенте нам нужен файл bootstrap.yml, который будет лежать в ресурсах:

spring: application: name: pyramid config: import: optional:configserver:http://localhost:8800 profiles: active: local cloud: config: fail-fast: true enabled: true username: configserver password: configserver security: user: name: actuator password: actuator roles: ACTUATOR_ADMIN server: port: 8082 #минимальная настройка Spring Actuator - ее нельзя переносить в config-server, потому что мы нуждаемся в обновлении через него по умолчанию management: endpoints: enabled-by-default: true web: exposure: include: "*" 

Здесь я привожу настройку для случая локального dev стенда, на котором сервер и клиент лежат на localhost, для переноса на сервер следует внести собственные правки адресов, портов и credentials. Секцию management вы также можете изменить под собственные нужды, добавив или более точно и безопасно перенастроив endpoints, для демонстрации я просто открыл все endpoints и опубликовал web, чтобы не возиться. В продуктовом приложении эта секция была настроена под нужды приложения, подробности которого здесь не обсуждаются. Фактически, данная настройка делает две вещи — предоставляет настройки для подключения к серверу Spring Cloud Config Server и предоставляет Spring Actuator с включенной примитивной авторизацией для того, чтобы использовать его для автообновления конфигураций.

В демо авторизацию я сделал самую простую, вы можете использовать любую настройку, которая требуется для вашего продуктива:

@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter < @Override protected void configure(HttpSecurity http) throws Exception < http .csrf().disable() .authorizeRequests() .requestMatchers(EndpointRequest.toAnyEndpoint()) .hasRole("ACTUATOR_ADMIN") .requestMatchers(PathRequest.toStaticResources().atCommonLocations()) .permitAll() .antMatchers("/") .permitAll() .antMatchers("/**") .authenticated() .and() .httpBasic() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); >> 

Ну вот, в общем-то и все самое главное о клиенте. Осталось добавить, что нужно разметить ваше приложение в нужных местах аннотациями @RefreshScope для передачи properties из конфигурации в код приложения там, где это вам нужно. Как это сделать, опять же можно посмотреть в статье, на которую я выше уже ссылался, или на мою статью, где этот вопрос также отчасти затронут для более редкого особенного случая. Полный код демо приложения можно посмотреть на github, в нем много не имеющего прямого отношения к данной статье (детали приложения с его специфическими нуждами), но все, что я здесь описал, вы найдете на своих местах.

Самое главное, что мы должны понять — без применения какого-либо механизма автообновления данный клиент будет забирать конфигурацию с сервера только при его загрузке или при кастомной инициации обновления. Если хранимая на сервере конфигурация будет изменена, клиент об этом ничего не узнает и будет использовать старые подгруженные значения до тех пор, пока мы не инициируем вручную запрос к клиенту на обновление конфигурации, в нашем случае мы используем для этого обращение к Spring Actuator, установленному на клиенте, по адресу https://client_url/actuator/refresh. Теоретически можно сделать и на самом клиенте bean с аннотацией @Scheduled, который будет опрашивать этот адрес с каким-то периодом, но это было бы совсем топорно, например, конфигурация будет загружаться заново независимо от того, были в ней обновления или нет, и клиент будет вхолостую выполнять массу совершенно не нужной работы в каждом периоде. Однако, если реализовать обращение к адресу Spring Actuator со стороны сервера и только при определенных условиях, то мы получим то, что требуется от нас в ТЗ. Поэтому так и поступим.

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

Также хочу пригласить всех желающих на бесплатный урок от OTUS, в рамках которого будут рассмотрены аспекты — что это и зачем нужно. Как создавать аспекты в Java используя разные технологии, и как они используются в Spring. Регистрация доступна по ссылке.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *