Spring Cloud Config为服务端和客户端提供了分布式系统的外部化配置支持。配置服务中心采用Git的方式存储配置文件,所以咱们很容易部署修改,有助于对环境配置进行版本管理。git
1.1
新建模块config-server
pom文件github
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud</artifactId> <groupId>com.feng</groupId> <version>0.0.1</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>config-server</artifactId> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies> </project>
1.2
application.ymlspring
server: port: 8030 eureka: client: serviceUrl: defaultZone: http://localhost:8010/eureka/ #eureka服务注册地址 # git管理配置 spring: cloud: config: server: git: uri: https://github.com/fengzp/config/ #git仓库地址 searchPaths: demo* #搜索路径 # username: username # password: password application: name: config-server
1.3
ConfigApplication,添加EnableConfigServer标识是一个配置中心服务apache
/** * @author fengzp * @date 17/5/4 * @email fengzp@gzyitop.com * @company 广州易站通计算机科技有限公司 */ @SpringBootApplication @EnableConfigServer @EnableDiscoveryClient public class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); } }
1.4
在配置的git仓库下新建一个demo1的文件夹,在里面建立一个叫client-a-dev.properties的配置文件
文件中随便加上两个配置bootstrap
ip=192.168.30.51 port=9999
启动模块,而后打开 http://localhost:8030/client-a/dev
app
说明读取配置成功maven
这里说明一下http请求读取配置的匹配规则:分布式
/{application}/{profile}[/{label}] /{application}-{profile}.yml /{label}/{application}-{profile}.yml /{application}-{profile}.properties /{label}/{application}-{profile}.properties
2.1
修改client-a模块
pom文件新增依赖测试
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
2.2
bootstrap.yml添加相关配置后rest
server: port: 8910 eureka: client: serviceUrl: defaultZone: http://localhost:8010/eureka/ spring: application: name: client-a cloud: config: discovery: enabled: true #开启经过服务来访问Config Server的功能 service-id: config-server profile: dev label: master
2.3
在TestController添加测试方法
@RestController public class TestController { @Autowired RestTemplate restTemplate; @RequestMapping("/hi") @HystrixCommand(fallbackMethod = "hiFallback") public String hi(@RequestParam String id){ return restTemplate.getForObject("http://service-a/hi?id="+id, String.class); } public String hiFallback(String id) { return "hi, " + id + ", error!"; } @Value("${ip}") private String ip; @Value("${port}") private String port; @RequestMapping("/getProperties") public String getProperties(){ return ip + " : " + port; } }
启动模块后打开 http://localhost:8910/getProperties
说明读取配置成功