Spring Cloud配置中心(Config)配置文件命名跟git分支及配置读取的关系

一、@Value注解读取配置

      Spring框架支持使用@Value注解的方式来获取 .properties文件中的配置值,这样可以大大简化读取配置文件的代码。读取方式如下:

@Slf4j
@Service
public class OmsShipmentServiceImpl implements OmsShipmentService {
    @Autowired
    private OmsOrderDAO omsOrderDAO;

    @Autowired
    private OmsOrderContactDAO omsContactDAO;

    @Value("${myConfig1.config1}")
    private String config1;

    @Value("${myConfig2.config2}")
    private String addTrackingUri;
    
    ... ...
}

    配置文件 {micro_service_name}-{branch_name}-{environment_name}.yml配置如下:

myConfig1:
  config1: configValue1
myConfig2:
  config2: configValue2

二、配置服务配置加载

     1、配置服务默认配置

          通过查看Spring Cloud Config 源码时会发现,在spring-cloud-config-server.jar包中有一个默认配置文件configserver.yml,当你的应用程序启动的时候没有读取到配置服务的配置文件,就会读取配置中心的默认配置,默认使用地址localhost:8888,默认读取Git地址为:https://github.com/spring-cloud-samples/config-repo仓库中的配置文件,文件内容如下:

info:
  component: Config Server
spring
  application:
    name: configserver
  jmx:
    default_domain: cloud.config.server
 cloud:
   config:
     server:
       git:
         uri: https://github.com/spring-cloud-samples/config-repo
         repos:
           - patterns: multi-repo-demo-*
            uri: https://github.com/spring-cloud-samples/config-repo
server:
  port: 8888
management:
  context_path: /admin

   2、配置文件命名规则:

       /{application}/{profile}[/{label}]
       /{application}-{profile}.yml

       /{label}/{application}-{profile}.yml

       /{application}-{profile}.properties

       /{label}/{application}-{profile}.properties

      这些文件命名格式会按照“{application}-{profile}.properties(yml)”格式匹配配置文件。label对应的是Git上的分支名称,是一个可选参数,如果没有这个参数,默认会从master分支上进行查找,如果配置了label,则会找到对应的分支下面去读取配置文件。可以根据自己的需求,选择哪种配置路径来读取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值