#java #spring #spring-boot
#java #весна #spring-загрузка
Вопрос:
Есть ли какой-либо способ перезагрузить свойства PropertyPlaceholderConfigurer
и обновить @Value
средство визуализации?
@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws Exception {
final ClassPathResource classPathRessource = new ClassPathResource(PROPERTIES_FILE);
final Properties fileProperties = loadDbPropertiesFromInputStream(classPathRessource.getInputStream());
// Instantiate properties dataSource
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(fileProperties.getProperty(PROPERTY_KEY_DATABASE_DRIVER));
dataSource.setUrl(fileProperties.getProperty(PROPERTY_KEY_DATABASE_URL));
dataSource.setUsername(fileProperties.getProperty(PROPERTY_KEY_DATABASE_USERNAME));
dataSource.setPassword(fileProperties.getProperty(PROPERTY_KEY_DATABASE_PASSWORD));
// Init PropertyPlaceholderConfigurer
final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
propertyPlaceholderConfigurer.setLocation(classPathRessource);
// Add properties from defined database
propertyPlaceholderConfigurer.setPropertiesArray(ConfigurationConverter.getProperties(getDatabaseConfiguration(dataSource)));
return propertyPlaceholderConfigurer;
}
Свойства загружаются из базы данных, и если база данных изменится, я должен перезапустить серверный сервер.. Итак, есть ли какие-либо способы избежать этого?
Спасибо
Комментарии:
1. Вам стоит взглянуть на весеннее облако. idk, если это позволяет, из базы данных, но это возможно из файлов с версиями
Ответ №1:
У вас есть два варианта :
- Через привод загрузки пружины
- Через Spring Cloud Bus
Вариант 1: через привод загрузки пружины.
Добавьте spring-boot-starter-actuator
зависимость в pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Когда вы добавляете новые изменения и хотите это увидеть, вам нужно вызвать этот URL :
http://ip:port/actuator/refresh
Но проблема в том, что обновление происходит на отдельном сервере.
Вариант 2: через Spring Cloud Bus
Но для этого вам нужно использовать некоторую систему очередей сообщений, такую как Kafka, RabbitMQ и так далее.
Я буду показывать только с помощью RabbitMQ.
-
Сначала установите Rabbit MQ и запустите его
-
Добавьте конфигурацию в application.properties для подключения к Rabbit MQ.
Читайте здесь : https://www.rabbitmq.com/tutorials/tutorial-one-spring-amqp.html
Добавьте spring-boot-starter-amqp
amp; spring-boot-starter-actuator
в pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Когда вы добавляете новые изменения и хотите это увидеть, вам нужно вызвать этот URL :
http://ip:port/actuator/bus-refresh
Плюс: обновление происходит на всех серверах.
Примечание: вы можете использовать @RefreshScope
для автоматического обновления средств @Value
визуализации. Пример :
@Configuration
@RefreshScope
public class AppConfig {
@Value("${some.value}")
private String value;
@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws Exception {
final ClassPathResource classPathRessource = new ClassPathResource(PROPERTIES_FILE);
final Properties fileProperties = loadDbPropertiesFromInputStream(classPathRessource.getInputStream());
// Instantiate properties dataSource
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(fileProperties.getProperty(PROPERTY_KEY_DATABASE_DRIVER));
dataSource.setUrl(fileProperties.getProperty(PROPERTY_KEY_DATABASE_URL));
dataSource.setUsername(fileProperties.getProperty(PROPERTY_KEY_DATABASE_USERNAME));
dataSource.setPassword(fileProperties.getProperty(PROPERTY_KEY_DATABASE_PASSWORD));
// Init PropertyPlaceholderConfigurer
final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
propertyPlaceholderConfigurer.setLocation(classPathRessource);
// Add properties from defined database
propertyPlaceholderConfigurer.setPropertiesArray(ConfigurationConverter.getProperties(getDatabaseConfiguration(dataSource)));
return propertyPlaceholderConfigurer;
}
}
Ответ №2:
Да, Spring предоставляет Spring cloud bus для такого случая, вы можете использовать его для обновления данных без перезапуска сервера, более того, вы можете использовать его для обновления нескольких экземпляров для вашего приложения.