分布式配置中心
微服务架构中,每个项目都有一个yml配置,管理起来麻烦。要使用spring cloud config来统一管理
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。在spring cloud config 组件中,分两个角色,一是config server,二是config client
代码实现
github上面有配置库
配置服务端
1.创建springcloud config服务端模块aigou_config666
2.导jar包
<dependencies>
<!--springboot支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--eureka客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--配置中心支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
3.配置yml文件
server:
port: 6666
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka #注册到注册中心
instance:
prefer-ip-address: true #显示ip
spring:
application:
name: spring-cloud-config-server #在注册中心显示的主机名
cloud:
config:
server:
git:
uri: https://github.com/wbls8411/application_eureka_server.git #git文件地址
username: ************* #github的账户名
password: ************* #gitHun的密码
4.创建启动类ConfigApplication666
@SpringBootApplication
@EnableEurekaClient //加入注册中心
@EnableConfigServer //启用配置服务端
public class ConfigApplication666 {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication666.class);
}
}
5.访问localhost:7001
配置客户端(服务提供者)
Eureka注册中心,configserver需要有自己的yml配置文件,其他的都是客户端,从github上获取
配置中心从github上获取配置文件后需要注册到注册中心,所以必须先启动注册中心
1.创建服务端模块
2.导jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--配置中心支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
3.配置bootstrap.yml文件
spring:
cloud:
config:
name: plat_application #github上面名称
profile: dev #环境
label: master #分支
uri: http://localhost:6666 #配置服务器
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka #告诉服务提供者要把服务注册到哪儿 #单机环境
instance:
prefer-ip-address: true #显示客户端真实ip
4.创建启动类ServiceApplication8002
@SpringBootApplication
@EnableEurekaClient //表示是eureka的客户端
public class ServiceApplication8002 {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication8002.class);
}
}