SpringCloud之配置中心-Config

Config-Server

Spring Cloud Config 是 Spring Cloud 团队创建的一个全新项目,用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持, 它分为服务端与客户端两个部分。服务端称为分布式配置中心, 它是一个独立的微服务应用, 用来连接配置仓库并为客户端提供获取配置信息、 加密/解密信息等访问接口;客户端微服务架构中的各个微服务应用或基础设施, 它们通过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。
在这里插入图片描述

Spring Cloud Config 实现了对服务端和客户端中环境变量和属性配置的抽象映射, 所以它除了适用于 Spring 构建的应用程序之外,也可以在任何其他语言运行的应用程序中使用。 由于 Spring Cloud Config 实现的配置中心默认采用 Git 来存储配置信息, 所以使用 Spring Cloud Config 构建的配置服务器,天然就支持对微服务应用配置信息的版本管理, 并且可以通过 Git 客户端工具来方便地管理和访问配置内容。 当然它也提供了对其他存储方式的支持, 比如 SVN 仓库、 本地化文件系统。

快速入门

配置中心服务

  • 在码云(GITEE)新建配置文件(可选GitHub、GitLab)

在码云新建项目config-server,在新项目下新建配置文件夹config,在config下创建application-test.properties,配置文件命名规则应尽可能使用:{application}-{profile}.{properties|yml}

在这里插入图片描述

  • config-server/config/application-test.properties
name=mask
age=18
  • pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  • 项目中application.properties
server.port=8081
spring.cloud.config.server.git.uri=https://gitee.com/mask_0407/config-server.git
spring.cloud.config.server.git.username=****** #码云账号
spring.cloud.config.server.git.password=****** #码云密码
spring.cloud.config.server.git.search-paths=/config
  • App.java
@SpringBootApplication
@EnableConfigServer
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

启动项目后访问:http://localhost:8081/application-test.properties
在这里插入图片描述

Config-Client

  • pom.xml
		<!--config client依赖-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<!--ConfigurationProperties类所需依赖,手动添加的-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
  • 码云中application-test.properties
server.port = 8082
name=mask
age=18
  • bootstrap.properties
server.port = 8082
spring.application.name = application #对应application-test.properties 中的application
spring.cloud.config.profile = test #对应application-test.properties 中的test
spring.cloud.config.uri=http://localhost:8081 # config-server 地址
# 开启所有的健康检查
management.endpoints.web.exposure.include=*
  • AppClient
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class AppClient {
	@Value("${server.port}")
	private String port;
	public static void main(String[] args) {
		SpringApplication.run(AppClient.class, args);
	}

	@RequestMapping("print")
	public String print() {
		return port;
	}
}

启动项目访问http://localhost:8082/print
在这里插入图片描述

发布了19 篇原创文章 · 获赞 8 · 访问量 4537

猜你喜欢

转载自blog.csdn.net/M283592338/article/details/105043551