7.SpringCloud-Config

提到分布式配置文件管理,我们会想到ZooKeeper,Spring Cloud Config也提供了分布式环境读取配置文件的支持,看一下是如何使用。

1.为了保证高可用性,防止Config Server不能提供服务,把多个Config Server注册到Eureka Server,首先创建Eureka Server

2.在启动类加入注解

@EnableEurekaServer

3.修改配置文件

server:
  port: 8889

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

4.创建Config Server工程

pom文件依赖如下

<dependencies>
   <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
   </dependency>

   <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-config-server</artifactId>
   </dependency>

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>
</dependencies>

5.在启动类加入注解

@EnableConfigServer

6.修改配置文件

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/gaojingyuan/springcloud
          searchPaths: config
          username:
          password:
      label: master
server:
  port: 8010
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8889/eureka/

7.启动工程
使用以下2个路径请求foo的默认和开发配置文件
http://localhost:8010/config-client/default

http://localhost:8010/config-client/development

上述2个请求分别对应https://github.com/gaojingyuan/springcloud/tree/master/config中的2个配置文件

配置文件名称必须根据一定规则定义才能这么访问
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

我们可以换一个端口比如8011,再次启动一个Config Server,以实现集群,提高可用性。

8.下面创建Config Client工程

9.启动类加入服务,验证参数是否被注入

@SpringBootApplication
@RestController
public class ConfigclientApplication {

   public static void main(String[] args) {
      SpringApplication.run(ConfigclientApplication.class, args);
   }

   @Value("${project}")
   String project;

   @RequestMapping(value = "/hi")
   public String hi(){
      return project;
   }

}

10.因为要加载的配置文件可能包括数据库密码等初始化配置,所以注意要修改bootstrap.yml而不是application.yml

spring:
  application:
    name: config-client
  cloud:
    config:
      label: master
      profile: development
      discovery:
        enabled: true
        serviceId: config-server
server:
  port: 8012
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8889/eureka/

要注意配置中profile: development,与git服务器存储的文件名中的profile要一致

11.依次启动ConfigEurekaServer,Config Server,Config Client工程,
访问Config Client工程查看结果

猜你喜欢

转载自blog.csdn.net/gaojingyuan/article/details/79038485