Spring Cloud(9):Config配置中心

Config配置中心作用简单来讲:统一配置,方便管理

开源配置中心:

1.百度Disconf

2.阿里Diamand

3.Spring Cloud Config

搭建Config-Server

快速上手:

选择依赖:Eureka和Config

选取Eureka原因:保证高可用

 启动类加入注解:

package org.dreamtech.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

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

}

配置:

Eureka-Server的搭建:https://www.cnblogs.com/xuyiqing/p/10861541.html

使用Git服务器:我使用的是Github,新建一个测试仓库

spring.application.name=config-server
server.port=9100
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
spring.cloud.config.server.git.uri=https://github.com/EmYiQing/SpringCloudTest
spring.cloud.config.server.git.username=EmYiQing
spring.cloud.config.server.git.password=xxxxxx

在Github上新建一个配置文件做测试:

测试:

启动项目Eureka-Server->Config-Server

查看注册中心:成功

访问localhost:9100:报错

访问http://localhost:9100/product-service.yml:拿到刚才在Github新建的配置文件,成功

如果我们访问http://localhost:9100/product-service.properties?

那么Config会直接把YML转化为properties文件,很强大

注意:Git上的配置文件格式一定不能出错

还可以做一些默认配置:比如超时时间和默认分支

spring.cloud.config.server.git.timeout=5
spring.cloud.config.server.git.default-label=master

有了Server当然也要有Client:

在服务模块引入依赖

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

将配置文件application.yml更名为bootstrap.yml:

进行三项配置:

1.Eureka-Server-URL

2.该服务模块名称

3.Config配置中心在Eureka-Server的名称和启用

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: product-service
  cloud:
    config:
      discovery:
        service-id: CONFIG-SERVER
        enabled: true

启动项目耗时将会更长,因为读取Git服务器配置文件是耗时的操作

Config配置中心使用的注意事项:

1.保证Git服务器的配置文件格式正确

2.Git服务器的配置文件建议采用分支进行区分,不推荐使用后缀区分

比如使用/test/product-service.yml代替/product-service-test.yml

然而到这里还是没有结束,比如配置文件的动态更新等等,这些功能在以后实现

猜你喜欢

转载自www.cnblogs.com/xuyiqing/p/10892785.html