#java #spring-boot #spring-cloud-config
#java #spring-boot #spring-cloud-config
Вопрос:
Я внедряю конфигурацию Spring Cloud, но клиенты не извлекают конфигурацию автоматически… Когда я запускаю, мой клиент получает данные с сервера правильно, но никогда не извлекает их снова.
Это мой сервер CloudConfig.
@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
public class CloudConfigApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConfigApplication.class, args);
}
}
aplication.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9091/eureka
server:
port: 8888
spring:
application:
name: config-server
cloud:
config:
server:
bootstrap: true
health:
enabled: true
native:
searchLocations: file:${user.dir}/src/main/resources/configs/
profiles:
active: native
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>CloudConfig</groupId>
<artifactId>CloudConfig</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>CloudConfig</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<!-- 3a) Dependency for spring-cloud-config-Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!-- 3b) Dependency for testing boot projects -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
/src/main/resources/config/CloudConfigClient.yaml
test: aaaaa
test2: 1111
Клиент SpringCloud
@EnableScheduling
@EnableDiscoveryClient
@SpringBootApplication
@EnableAutoConfiguration
public class CloudConfigClient {
@Value("${test}")
private String myProperty;
public static void main(String[] args) {
SpringApplication.run(CloudConfigClient.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Scheduled(fixedDelay =1000)
public void printProperty() {
System.out.println("Value of property "myProperty": " myProperty);
}
}
bootstrap.yaml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9091/eureka
server:
port: 7004
datasource:
driver-class-name: org.h2.Driver
application:
name: CloudConfigClient
cloud:
config:
uri: http://localhost:8888
fail-fast: true
max-attempts: 20
max-interval: 15000
initial-interval: 10000
Pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Это журнал вывода:
2020-11-20 23:33:12.747 INFO 16764 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2020-11-20 23:33:13.510 INFO 16764 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=CloudConfigClient, profiles=[default], label=null, version=null, state=null
2020-11-20 23:33:13.510 INFO 16764 --- [ restartedMain] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='file:D:/CloudConfig/src/main/resources/configs/CloudConfigClient.yaml'}]}
...
...
Value of property "myProperty": aaaaa
Value of property "myProperty": aaaaa
Ответ №1:
если вы хотите, чтобы ваша конфигурация обновлялась, вы должны использовать @RefreshScope spring doc, конфигурация не будет обновляться по волшебству, потому что вы вызываете @Scheduled .
Но в зависимости от того, как вы извлекаете значение в компоненте конфигурации, они могут быть ограничением, и @RefreshScope не будет работать refreshscope
Я предлагаю создать компонент @ConfigurationProperties и аннотировать с помощью @RefreshScope, когда вы нажмете на конечную точку привода / обновить, все должно обновиться или, возможно, комбинация @Schedule, вы могли бы достичь того, чего хотите
Комментарии:
1. Я думал, что клиент CloudConfig может автоматически извлекать или, возможно, нуждается в некоторой конфигурации в application.properties… но если это не так… Я могу реализовать на своем сервере CloudConfig функцию вызова микросервиса / привода / обновления при изменении файла конфигурации.