spring java 动态获取consul K/V
1.springConsul配置kv路径
spring:cloud:consul:enabled: ${CONSUL_ENABLED:true}host: ${CONSUL_HOST:localhost}port: ${CONSUL_PORT:8500}config:prefix: ${CONSUL_CONFIG_PREFIX:config} #consul kv前缀fail-fast: ${CONFIG_FAIL_FAST:false} #两个fail-fast结合实现启动服务时当consul不存在时服务能正常启动format: YAML # 表示consul上面文件的格式 有四种 YAML PROPERTIES KEY-VALUE FILESdata-key: ${CONSUL_DATA_KEY:data} #表示consul上面的KEY值(或者说文件的名字) 默认是data# watch选项为配置监视功能,主要监视配置的改变watch:enabled: truedelay: ${WATCH_DELAY:${consul.watch.delay:2000}}wait-time: ${WATCH_WAIT-TIME:20}default-context: ${CONSUL_DEFAULT_CONTEXT:baseconfig}prefixes:- configdiscovery:fail-fast: ${DISCOVERY_FAIL_FAST:false}catalogServicesWatchDelay: ${CONSUL_DISCOVERY_CATALOG_SERVICES_WAtCH_DELAY:2000} #目录监听延迟heartbeat:enabled: ${HEARTBEAT_ENABLE:true} #两个fail-fast结合实现启动服务时当consul不存在时服务能正常启动reregister-service-on-failure: ${HEARTBEAT_REREGISTER:true} #当ttl重试时,若服务不存在是否重新注册服务ttl: ${HEARTBEAT_TTL_VALUE:20}senabled: true # 启用服务发现prefer-ip-address: true # 表示注册时使用IP而不是hostnamehostname: localhosthealth-check-path: ${CONSUL_HEALTH_CHECK_PATH:${management.endpoints.web.base-path:/actuator}/health} #consul默认健康检查地址,可以通过management进行修改health-check-critical-timeout: ${HEALTH_CHECK_CRITICAL_TIMEOUT:60s} # 健康检查失败多长时间后,取消注册service-name: ${spring.application.name}instance-id: ${spring.application.name}-${spring.cloud.client.ip-address}-${server.port} # 服务idtags:- ${TAGNAME_GRAYSCALE:graycaletag}=${GRAYSCALE_TAG:${spring.application.name}-${SERVER_SEQUENCE:1}}- ${TAGNAME_SERVICEEXT:serviceext}=${SERVICE_EXT:default}query-passing: true #仅发现健康状态的服务
重点:
spring.cloud.consul.config.prefix consulKV前缀,低版本仅能设置一个
spring.cloud.consul.config.data-key consulKV 最后一级
spring.cloud.consul.config.default-context consulKV中间层级
通过该配置,服务会从consul的KV路径config/baseconfig/data 下的data信息
2.自动注入consulKV到服务中
consul KV 配置为
当服务启动时,服务会从consul的KV对应路径下获取配信息到服务中,再服务中通过注解ConfigurationProperties来获取
@Getter
@Setter
@Component
@ConfigurationProperties("myconsul.kv.test")
public class MyConsulKvTest {private String name;private String id;
}
当修改consulKV后服务中 MyConsulKvTest 这个bean也会自动更新