
1、创建spring-cloud-houge-config子项目,测试需要的项目入下
2、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId></dependency>
3、配置文件
aoolication.properties
spring.application.name=config-server
server.port=8001
#读取本地文件
spring.profiles.active=native
在src/main/resources下添加config-dev.properties,config-test.properties,config-pro.properties
每个配置文件中都写一个属性env,属性值分别是 dev/test/pro
4、启动类
@EnableConfigServer //激活对配置中心的支持
@SpringBootApplication
public class ConfigServerApplication { public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
} }
5、启动config
http://localhost:8001/config-dev.properties
6、启动测试服务(spring-cloud-houge-provider)
a、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
b、配置文件
bootstrap.properties
spring.cloud.config.name=config
spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:8001/
c、启动类
@SpringBootApplication
@EnableDiscoveryClient //使项目有服务注册功能
public class ProviderApplication { public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
d、添加测试代码
@RestController
//@RefreshScope
@RequestMapping("/dynasty")
public class DynastyController { @Value("${env}")
private String env; @RequestMapping("/hello")
public String hello(@RequestParam String name) {
return "hello, " + name + ":" + env;
}
}
e、http://localhost:9000/dynasty/hello?name=houge
6、refresh、开启更新
手动修改config的配置文件,调用端不会立即更新,需修改调用端代码
@RestController
@RefreshScope // 使用该注解的类,会在接到SpringCloud配置中心配置刷新的时候,自动将新的配置更新到该类对应的字段中
@RequestMapping("/dynasty")
public class DynastyController { @Value("${env}")
private String env; @RequestMapping("/hello")
public String hello(@RequestParam String name) {
return "hello, " + name + ":" + env;
}
}
springboot 1.5.X 以上默认开通了安全认证,所以需要在配置文件application.properties
添加以下配置
management.security.enabled=false
7、测试
修改config-dev.properites中env=local
以post请求的方式来访问http://192.168.0.131:9000/refresh 就会更新修改后的配置文件