我对 Spring Cloud 和 Spring 外部配置的概念非常陌生,实际上是昨天开始的。
我创建了一个配置服务器,从本地 Git 存储库中选择配置,一个微服务也是配置客户端和一个 Eureka 驱动的服务发现服务器。
以下是我主要从互联网上的各种资源中借来的代码 -
配置服务器 - application.yml:
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: file:///${user.home}/config-repo
配置服务器 - 主类(引导程序)
@EnableConfigServer
@SpringBootApplication
public class CloudConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConfigServerApplication.class, args);
}
}
config-repo 是我机器上的本地 git repo,并且有一个 .yml 文件,其中包含配置客户端应用程序的名称,即 authmanager.yml
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
healthcheck:
enabled: true
lease:
duration: 5
spring:
application:
data:
mongodb:
host: localhost
port: 27017
database: edc_mc
logging:
level:
org.exampledriven.eureka.customer.shared.CustomerServiceFeignClient: FULL
现在运行配置服务器后,下面是端点http://localhost:8888/authmanager/default的输出-
{"name":"authmanager","profiles":["default"],"label":"master","version":"0ca6ca7b4502b9bb6ce1bf8efeb25516682cf79a","propertySources":[{"name":"file:///C:\\Users\\username/config-repo/authmanager.yml","source":{"eureka.client.serviceUrl.defaultZone":"http://127.0.0.1:8761/eureka/","eureka.client.healthcheck.enabled":true,"eureka.client.lease.duration":5,"spring.application.data.mongodb.host":"localhost","spring.application.data.mongodb.port":27017,"spring.application.data.mongodb.database":"db_name","logging.level.org.exampledriven.eureka.customer.shared.CustomerServiceFeignClient":"FULL"}}]}
微服务+Config客户端代码——
bootstrap.yml -
server:
port: 9097
spring:
application:
name: authmanager
cloud:
config:
uri: http://localhost:8888
客户端 - 主类(引导程序) -
@SpringBootApplication
@EnableDiscoveryClient
@EnableWebMvc
public class CloudLoginManagerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudLoginManagerApplication.class, args);
}
}
配置客户端中的控制器类,我想在其中使用配置文件属性 -
@RefreshScope
@RestController
@RequestMapping("/auth")
public class MyController {
@Value("${spring.application.data.mongodb.database}")
String env_var;
为了清楚起见,跳过其余代码。
这是我得到的错误 -
Could not resolve placeholder 'spring.application.data.mongodb.database' in string value "${spring.application.data.mongodb.database}"
server.port 等其他属性没有问题。
我也尝试过 Environment 接口方式,但那也返回 null 。
请任何指点,我现在几乎走到了死胡同。
谢谢,
阿杰