Config配置中心
Config为微服务架构中的微服务提供集中化的外部配置支持,配置服务器为各个不同微服务应用的所有环境提供了一个中心化的外部配置。
Config配置中心的基本使用,git中心存在文件
服务端
从git中拉取文件。
-
添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
-
主启动类
@SpringBootApplication @EnableConfigServer public class ConfigCenterApplication { public static void main(String[] args) { SpringApplication.run(ConfigCenterApplication.class, args); } }
-
application.yml配置文件
server: port: 3344 spring: application: name: cloud-config-center cloud: config: server: git: uri: https://gitee.com/talent-player/spring-cloud #github仓库名字 #搜索目录 search-paths: - spring-cloud #读取分支 label: master
客户端
连接服务端使用git中的配置文件。
-
添加客户端依赖以及bootstrap配置文件依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> </dependency>
-
bootstrap.yml配置文件
bootstrap也是一种配置文件,是系统级配置文件,加载时间比application早。
#分支名称 spring.cloud.config.label=master #配置文件名称 spring.cloud.config.name=config #读取后缀名称 spring.cloud.config.profile=dev #配置中心地址 spring.cloud.config.uri=http://localhost:3344
-
配置完即可使用${}来引入配置
由于bootstrap的加载时间比application时间早,bootstrap加载完后配置即可使用,所有可以在application中用${}引入配置。下面为application文件
server.port=8002 server.servlet.context-path=/sent #服务名称 spring.application.name=cloud-payment-service spring.datasource.driver-class-name=${spring.datasource.driver-class-name} spring.datasource.url=${spring.datasource.url} spring.datasource.username=${spring.datasource.username} spring.datasource.password=${spring.datasource.password} #指定mapper文件路径 mybatis-plus.mapper-locations=classpath:mapper/*.xml #开启日志输出 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #false表示向注册中心注册自己 eureka.client.register-with-eureka=true #false表示自己就是注册中心 eureka.client.fetch-registry=true #设置与eureka server交互地址查询服务和注册服务都依赖这个地址 eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka eureka.instance.instance-id=payment8002 eureka.instance.prefer-ip-address=true
java代码中也可通过@Value引入配置
@Value("${msg}") private String msg;