一、consul配置中心存在的问题:

我们使用consul作为配置中心时,在springboot项目的配置文件中一般会添加如下配置

spring:
  profiles:
    active: dev
  application:
    name: customer-service
  config:
    import: optional:consul:localhost:8500
  cloud:
    consul:
      health-indicator:
        use-services-query: false
      # 配置中心相关配置
      config:
        enabled: true #是否启用配置中心功能
        format: yaml #设置配置值的格式
        data-key: ${spring.application.name} #配置key的名字,由于Consul是K/V存储,配置存储在对应K的V中
        watch:
          # 是否开启自动刷新,默认值 true 开启
          enabled: true
          # 刷新频率,单位:毫秒,默认值 1000
          delay: 10000
        prefixes: config

按照上面的配置,从程序启动日志中可以发现程序会到consul服务端的如下4个地方查询对应的配置。

问题: 也就是说会发出http请求4次到服务端,然而我们的配置一般在固定的一个路径下(上面4个中的一个),显然请求4次是有点浪费性能。

二、解决方法

我们需要了解consul为什么会到上面提到的4个路径里找配置呢?通过浏览源码我们发现是在如下的源码中指定的:

而且同时发现: 有getCustomContexts方法是可以自定义查找路径的

具体的配置如下

spring:
  profiles:
    active: dev
  application:
    name: customer-service
  config:
    import: optional:consul:localhost:8500config/application
  cloud:
    consul:
      health-indicator:
        use-services-query: false
      # 配置中心相关配置
      config:
        enabled: true #是否启用配置中心功能
        format: yaml #设置配置值的格式
        data-key: ${spring.application.name} #配置key的名字,由于Consul是K/V存储,配置存储在对应K的V中
        watch:
          # 是否开启自动刷新,默认值 true 开启
          enabled: true
          # 刷新频率,单位:毫秒,默认值 1000
          delay: 10000
        prefixes: config

这次再启动通过日志发现只发起请求一次:

 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐