Springcloud学习——Github管理分布式配置

1. Github项目地址 https://github.com/zengzhen1994/springboot-learning (选择Springcloud/Springcloud-learning-3)

2. 这一章节主要介绍利用Github管理分布式配置,下一篇会融合之前的Eureka注册、消费等整合分布式配置和RabbitMQ消息总线。

3.  必要性

Github的优点就不用说了,在一个分布式系统中,往往需要将一些配置信息从代码中抽取出来。这样在维护起来的时候就方便修改。将配置储存在git上,它会对配置进行储存管理,各个微服务需要配置信息的时候只需要去获取Git上写好的配置就行了,这样就不用重复配置,形成配置共享。Git会通过微服务的用户名和文件名提取出相应的配置文件,高效快捷地管理配置文件。

4. 准备工作

4.1 搭建配置服务器

该服务器作用主要是连接Github,充当一个中转站。所有的配置客户端发送请求到服务端,服务端再获取git上相应的配置文件。

服务端,导入配置服务器的相关依赖包

		
			org.springframework.cloud
			spring-cloud-config-server
		
之后在启动程序里开启config-server注解@EnableConfigServer

之后就是配置和github的连接信息,写在application-properties,端口我这里设置的是24,一会用来接收请求

spring.application.name=ConfigServer
server.port=24
#这里配置你的github地址
spring.cloud.config.server.git.uri=https://github.com/zengzhen1994/springboot-learning/
#这里配置你要储存的配置文件路径
spring.cloud.config.server.git.searchPaths=springcloud/springcloud-learning-3/config
#这里是你的github的用户名
spring.cloud.config.server.git.username=username
#这里是你的github的密码
spring.cloud.config.server.git.password=password
到这里,服务器配置完成,启动程序。

4.2 搭建配置客户端

当客户端需要配置信息的时候,就可以发送请求到config-server上去获取相应的请求。pom里导入依赖

		
			org.springframework.cloud
			spring-cloud-starter-config
		
编写一个bootstrap.properties,name表示你的应用名,profile是你请求的配置文件名字。当config-server接收到请求时,就会去获取zz-info.properties的配置文件。

#bootstrap.properties初始化在application.properties之前
#我要请求的配置是zz-info,则name是zz,profile是info
spring.application.name=zz
spring.cloud.config.profile=info
#这里请求发往config-server
spring.cloud.config.uri=http://localhost:24/
server.port=8080
以下是我 springcloud/springcloud-learning-3/config文件里配置文件信息

Springcloud学习——Github管理分布式配置_第1张图片

 获取完配置信息,可以写一个controller测试一下客户端是否获取成功

package com.zz.springcloud.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope
@RestController
class ConfigController {

    @Value("${name}")
    private String name;
    @Value("${age}")
    private String age;
	@RequestMapping("/info")
    public String getInfo() {

        return "name:"+name+"---------"+"age:"+age;
    }



}
之后打开浏览器,访问localhost:8080/info/ 显示信息如下,则表示分布式配置成功。

Springcloud学习——Github管理分布式配置_第2张图片








你可能感兴趣的:(Springcloud)