搭建Spring Cloud Config服务端
- 引入依赖:在
pom.xml
中添加Spring Cloud Config Server相关依赖。例如在基于Maven的Spring Boot项目中:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
- 配置文件:在
application.yml
或application.properties
中进行配置。指定Git仓库地址(配置文件存储在此)等信息。如:
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/yourusername/yourconfigrepo
- 启用服务:在Spring Boot主类上添加
@EnableConfigServer
注解,以启用Config Server功能。
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);
}
}
微服务客户端集成Spring Cloud Config获取配置信息
- 引入依赖:在微服务的
pom.xml
中添加Spring Cloud Config Client依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
- bootstrap配置:创建
bootstrap.yml
或bootstrap.properties
文件,配置连接到Config Server的信息,如:
spring:
application:
name: your - microservice - name
cloud:
config:
uri: http://localhost:8888
fail - fast: true
- 获取配置:在微服务中通过
@Value
注解或Environment
对象获取配置信息。例如:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@Value("${your.config.key}")
private String configValue;
@GetMapping("/config")
public String getConfig() {
return configValue;
}
}
搭建Apollo配置中心服务端
- 下载安装包:从Apollo官方GitHub仓库下载服务端安装包,解压到指定目录。
- 数据库配置:创建Apollo所需的数据库,导入SQL脚本(
apolloconfigdb.sql
和apolloportaldb.sql
)。
- 修改配置:编辑
config
目录下的application.yml
,配置数据库连接等信息。
- 启动服务:在解压目录下执行
bash scripts/startup.sh
启动Apollo服务端,包括Config Service和Portal Service。
微服务客户端集成Apollo获取配置信息
- 引入依赖:在微服务
pom.xml
中添加Apollo客户端依赖:
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo - client</artifactId>
<version>最新版本号</version>
</dependency>
- 配置Apollo地址:在
application.properties
或application.yml
中配置Apollo Meta Server地址:
apollo.meta=http://localhost:8080
- 获取配置:通过
ApolloConfig
对象获取配置信息。例如:
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@GetMapping("/config")
public String getConfig() {
Config config = ConfigService.getAppConfig();
return config.getProperty("your.config.key", "default - value");
}
}