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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值