springcloud学习第五篇

springcloud学习第五篇

一、Config配置中心快速使用

1.添加依赖

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

2.添加配置

server:port: 8888
spring:cloud:config:server:git:uri: https://github.com/config/config-repo

3.启动类

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

4.微服务集成配置客户端 (Config Client)

4.1.添加依赖

在微服务项目中引入 spring-cloud-starter-config 依赖。

4.2.配置服务端地址

在微服务的 bootstrap.yml(优先级高于 application.yml)中配置。

spring:application:name: service-namecloud:config:uri: http://localhost:8888profile: testlabel: master

4.3.使用配置

通过标准的 @Value 注解或 @ConfigurationProperties 来注入配置值。如需支持配置动态刷新,在类上添加 @RefreshScope 注解

4.4.配置文件查找规则

Config Client 会通过 /{application}/{profile}/{label} 的规则来定位配置文件。

  • application:客户端 spring.application.name 的值。
  • profile:客户端当前激活的环境 (如 dev, prod)。
  • label:Git分支,默认为 master

例如,一个名为 user-service,激活 dev 环境的服务,会查找 user-service-dev.yml 文件。

本文来自博客园,作者:TheLifelongLearner,转载请注明原文链接:https://www.cnblogs.com/The-Lifelong-Learner/p/20642114