这篇文件简单解释下如何使用spring-cloud来搭建分布式配置中心
其实学了spring-boot后再来看spring-cloud是非常容易的。
在git仓库中创建相关文件具体参见 https:///majinding/TM-springcloud-demo-config
创建配置中心服务端1。 创建config-server项目 2。 在pom中引入config-server的依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
3。 编写application.yml
server: port: 8888 spring: application: name: config-server cloud: config: server: git: uri: https:///majinding/TM-springcloud-demo-config # username: majinding888@foxmail.com # password: default-label: master search-paths: tm-1
4。 编写主启动类
@SpringBootApplication @EnableConfigServer public class ConfigServerApplication {
public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
在启动类上增加 @EnableConfigServer
5。 启动项目
创建配置中心客户端1。 创建config-client项目 2。 在pom文件中增加config客户端的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
3。 编写application.yml
server: port: 8887 spring: application: name: config-client cloud: config: label: master profile: dev uri: http://localhost:8888/
4。 编写beanconfig类(用于存储获取git仓库中的参数)
@Configuration @RefreshScope public class BeanConfig {
@Value("${tm.name}") private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
5。 编写调用的Controller类
@RestController public class SayController { @Autowired private BeanConfig beanconfig;
@RequestMapping(value = "/say") public String say() { return beanconfig.getName(); }
}
6。 编写主启动类
@SpringBootApplication public class ConfigClientApplication {
public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); }
}
7。 启动项目,浏览器访问 http://localhost:8887/say
现在来看下项目已经成功读取到了git仓库中的变量值。到这里只是介绍了配置中心的简单基本用法。
配置中心服务注册到注册中心eureka中,集群化的高可用。在config-server项目中增加eureka依赖支持
- pom中加入eureka依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eurek</artifactId> </dependency>
- 在application.yml配置文件中增加eureka
eureka: client: registerWithEureka: true fetchRegistry: true service-url: defaultZone: http://localhost:8761/eureka/
在config-client项目中增加eureka依赖支持
- pom中加入eureka依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eurek</artifactId> </dependency>
- 在application.yml配置文件中增加eureka,并对config进行改造
``` server: port: 8887 spring: application: name: config-client cloud: config: label: master profile: dev discovery: enabled: true service-id: config-server
eureka: client: registerWithEureka: true fetchRegistry: true service-url: defaultZone: http://localhost:8761/eureka/
```
依次启动
- tm-eureka-server
- config-server
- config-client
在浏览器访问 http://localhost:8887/say
|