背景

很多使用SpringCloud微服务框架的工程都默认使用spring-cloud-config-server作为配置中心,我们的项目需要更便捷的部署,刚好注册中心已经使用consul了,就考虑是否将注册中心和配置中心合一,减少服务数目,方便更快部署。

实践

1 添加consul依赖

1.1 pom文件

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-bus</artifactId>
        </dependency>

我的依赖添加了两个,如果不需要动态刷新配置,可以省去spring-cloud-starter-consul-bus。

1.2 bootstrap文件

spring.application.name=user-service

#config
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
spring.cloud.consul.config.enabled=true
# 指定consul配置的文件夹前缀为
spring.cloud.consul.config.prefix=config
# 指定consul配置的配置文件为
spring.cloud.consul.config.data-key=data
# 指定consul配置的配置文件格式properties(maven),gradle为(YAML)
spring.cloud.consul.config.format=properties
# 指定consul配置的配置文件父路径  设置所有应用程序使用的文件夹名称,默认为applications
spring.cloud.consul.config.defaultContext=${spring.application.name}
spring.profiles.active=dev

2 在consul上设置工程配置

我的工程名称为user-service, 配置文件前缀为confg, 里面个格式properties

在这里插入图片描述

效果

我的代码非常简单,就只直接在controller中使用@Value引用了一属性,该属性在本地application.properties和远程consul中都配置了,启动后远程consul的配置覆盖了本地配置。—验证的consul配置生效。

第一个截图,bootstrap、application文件配置与consul上的配置
在这里插入图片描述

第二截图,演示swagger上获取该属性的实际值
在这里插入图片描述

参考内容

1, 官方文档 https://cloud.spring.io/spring-cloud-static/spring-cloud-consul/2.0.3.RELEASE/single/spring-cloud-consul.html
2, 官方示例, https://spring.io/projects/spring-cloud-consul#overview

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐