`

Spring Cloud之Config

阅读更多

  Spring Cloud中通过子项目spring-cloud-config实现了基于git、svn等的分布式配置管理,为微服务的构建提供便利条件。

 http访问规则

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

application:应用名称,对应客户端配置中的spring.config.name

profile:活动配置文件标识

label: 版本

服务端配置

1、pom.xml中依赖
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
 2、bootstrap.yml配置项
server:
  port: 8888
spring:
  cloud:
    config:
      server:
        git:
#          uri: https://github.com/hjguang/{application}
            uri: https://github.com/hjguang/cloud-config
management:
  security:
    enabled: false
3、启动主程序,添加相应注解
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(ConfigServerApp.class, args);

	}

}
4、启动验证  
http://localhost:8888/env

客户端配置

1、pom.xml添加依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
 2、bootstrap.yml
spring:
  application:
    name: config-client
  cloud:
    config:
      uri: http://localhost:8888
 #     profile: ${profile}

server:
  port: 8090

management:
  security:
    enabled: false
3、客户端获取配置代码
@RestController
@SpringBootApplication
public class ConfigClientApp {

	@Value("${db.url}") String url;
	@Value("${db.username}") String userName;
	@Value("${db.password}") String password;
	
	@RequestMapping("/dbconfiginfo")
	public String getValue() {
		return "URL :" + url + " UserName:" + userName + " Password:" + password;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(ConfigClientApp.class, args);
	}

}
 4、结果查看:http://localhost:8090/dbconfiginfo

URL :cc_url UserName:cc_user1 Password:cc_pw

使用profile

启动客户端时,添加参数--profile=test,客户端将获取配置仓库中config-client-test.properties中的配置内容

显示结果:URL :url-test UserName:test-u Password:test-pw

每个项目分配一个配置仓库地址

服务端配置文件的git url改为:uri: https://github.com/hjguang/{application}

示例结果:URL :url-test UserName:test-u Password:test-pw

 

项目地址

https://github.com/hjguang/spring-cloud

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics