aj1*_*984 4 spring-boot spring-cloud spring-cloud-netflix spring-cloud-config
我对Spring Cloud和Spring外部配置的概念很陌生,实际上是昨天开始的.
我创建了一个Config Server从本地Git存储库中挑选配置,一个微服务也是配置客户端和一个Eureka驱动的服务发现服务器.
以下是我主要从互联网上的各种资源中借用的代码 -
配置服务器 - application.yml:
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: file:///${user.home}/config-repo
Run Code Online (Sandbox Code Playgroud)
配置服务器 - 主类(引导程序)
@EnableConfigServer
@SpringBootApplication
public class CloudConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConfigServerApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
config-repo是我机器上的本地git repo,并且有一个.yml文件,其名称为config client application,即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
Run Code Online (Sandbox Code Playgroud)
现在运行配置服务器后,下面是端点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"}}]}
Run Code Online (Sandbox Code Playgroud)
微服务+配置客户端代码 -
bootstrap.yml -
server:
port: 9097
spring:
application:
name: authmanager
cloud:
config:
uri: http://localhost:8888
Run Code Online (Sandbox Code Playgroud)
客户 - 主类(引导程序) -
@SpringBootApplication
@EnableDiscoveryClient
@EnableWebMvc
public class CloudLoginManagerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudLoginManagerApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
配置客户端中的Controller类,我想使用配置文件属性 -
@RefreshScope
@RestController
@RequestMapping("/auth")
public class MyController {
@Value("${spring.application.data.mongodb.database}")
String env_var;
Run Code Online (Sandbox Code Playgroud)
为清晰起见,跳过其余的代码.
这是我得到的错误 -
Could not resolve placeholder 'spring.application.data.mongodb.database' in string value "${spring.application.data.mongodb.database}"
Run Code Online (Sandbox Code Playgroud)
像server.port这样的其他属性不会给出问题.
我也尝试过Environment接口方式,但那也返回null.
请指点,我现在几乎已经走到了尽头.
谢谢,
AJ
要启用云配置,您必须添加spring-cloud-starter-config到依赖项.您可以通过检查/ env(可能需要添加执行器)来查看哪些属性可用来验证.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5627 次 |
| 最近记录: |