本文目录导读:

我来为您提供一个完整的Spring Cloud Config配置中心案例,包括服务端和客户端。
项目结构
config-server-demo/
├── pom.xml
└── src/main/java/com/example/configserver/
├── ConfigServerApplication.java
└── controller/ConfigController.java
config-client-demo/
├── pom.xml
└── src/main/java/com/example/configclient/
├── ConfigClientApplication.java
└── controller/ConfigClientController.java
服务端实现
1 服务端pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
</parent>
<groupId>com.example</groupId>
<artifactId>config-server-demo</artifactId>
<version>1.0.0</version>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
</properties>
<dependencies>
<!-- Config Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 安全认证(可选) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2 服务端配置application.yml
server:
port: 8888
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://github.com/yourusername/config-repo # Git仓库地址
search-paths: # 搜索路径
- config-repo
username: your-username # Git用户名(如果仓库是私有的)
password: your-password # Git密码(如果仓库是私有的)
clone-on-start: true # 启动时自动clone
force-pull: true # 强制拉取
# 也可以使用本地文件系统
# native:
# search-locations: classpath:/config-repo
# 使用本地文件系统时需要配置
profiles:
active: git
# 安全认证(可选)
security:
user:
name: config-user
password: config-password
3 服务端启动类
package com.example.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
4 服务端测试控制器
package com.example.configserver.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigController {
@GetMapping("/health")
public String health() {
return "Config Server is running!";
}
}
客户端实现
1 客户端pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
</parent>
<groupId>com.example</groupId>
<artifactId>config-client-demo</artifactId>
<version>1.0.0</version>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
</properties>
<dependencies>
<!-- Config Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 健康检查 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 消息总线(用于动态刷新) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<!-- 安全认证(可选) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2 客户端bootstrap.yml配置
spring:
application:
name: config-client
cloud:
config:
uri: http://localhost:8888 # Config Server地址
username: config-user # 认证用户名(如果启用了认证)
password: config-password # 认证密码(如果启用了认证)
fail-fast: true # 快速失败
retry:
initial-interval: 1000
max-interval: 5000
max-attempts: 6
3 客户端application.yml配置
server:
port: 8080
spring:
profiles:
active: dev
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
management:
endpoints:
web:
exposure:
include: "*"
4 客户端启动类
package com.example.configclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
5 客户端配置属性类
package com.example.configclient.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@RefreshScope
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String name;
private String version;
private String environment;
private DatabaseConfig database = new DatabaseConfig();
// Getter 和 Setter
public static class DatabaseConfig {
private String url;
private String username;
private String password;
// Getter 和 Setter
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public DatabaseConfig getDatabase() {
return database;
}
public void setDatabase(DatabaseConfig database) {
this.database = database;
}
}
6 客户端测试控制器
package com.example.configclient.controller;
import com.example.configclient.config.AppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigClientController {
@Autowired
private AppConfig appConfig;
@Value("${spring.datasource.url:default-url}")
private String datasourceUrl;
@GetMapping("/info")
public Map<String, Object> getConfigInfo() {
Map<String, Object> result = new HashMap<>();
result.put("appName", appConfig.getName());
result.put("appVersion", appConfig.getVersion());
result.put("environment", appConfig.getEnvironment());
result.put("database", appConfig.getDatabase());
return result;
}
@GetMapping("/datasource")
public Map<String, String> getDatasource() {
Map<String, String> result = new HashMap<>();
result.put("url", datasourceUrl);
return result;
}
}
配置文件仓库结构
在Git仓库中创建配置文件:
1 config-client-dev.yml
app:
name: my-application
version: 1.0.0
environment: development
database:
url: jdbc:mysql://localhost:3306/dev_db
username: dev_user
password: dev_password
spring:
datasource:
url: jdbc:mysql://localhost:3306/dev_db
username: dev_user
password: dev_password
2 config-client-prod.yml
app:
name: my-application
version: 1.0.0
environment: production
database:
url: jdbc:mysql://prod-db-server:3306/prod_db
username: prod_user
password: prod_password
spring:
datasource:
url: jdbc:mysql://prod-db-server:3306/prod_db
username: prod_user
password: prod_password
运行和测试
1 启动顺序
- 启动Git仓库(或使用本地文件系统)
- 启动Config Server(端口:8888)
- 启动Config Client(端口:8080)
2 测试命令
# 检查Config Server是否运行 curl http://localhost:8888/health # 获取配置信息 curl http://localhost:8888/config-client/dev # 获取特定配置 curl http://localhost:8888/config-client-dev.yml # 测试客户端获取配置 curl http://localhost:8080/config/info
动态刷新配置
1 手动刷新特定客户端
curl -X POST http://localhost:8080/actuator/refresh
2 使用消息总线刷新所有客户端
curl -X POST http://localhost:8080/actuator/bus-refresh
高级配置示例
1 使用本地文件系统(开发环境)
# Config Server application.yml
spring:
profiles:
active: native
cloud:
config:
server:
native:
search-locations: classpath:/config-repo,file:/opt/config-repo
2 使用数据库存储
# Config Server application.yml
spring:
cloud:
config:
server:
jdbc:
sql: SELECT KEY, VALUE from PROPERTIES where APPLICATION=? and PROFILE=? and LABLE=?
order: 1
注意事项
- 配置文件命名规则:
{application}-{profile}.yml或{application}-{profile}.properties - bootstrap.yml 要先于 application.yml 加载
- 配置优先级:命令行 > 环境变量 > 配置文件
- @RefreshScope 注解用于实现配置动态刷新
- 生产环境建议使用RabbitMQ或Kafka作为消息总线
这个案例提供了完整的Spring Cloud Config配置中心实现,包括服务端、客户端、配置文件管理和动态刷新功能,您可以根据实际需求进行调整和扩展。