Spring Cloud学习day104:分布式配置中心

一、为什么需要使用配置中心 ?

1.服务配置的现状:

在微服务系统中,每个微服务不仅仅只有代码,他还需要连接其他资源,例如数据库的配置或功能性的开关等等。但是随着微服务系统的不断迭代,整个微服务系统可能会成为一个网状结构,这个时候就要考虑整个服务系统的扩展性、伸缩性、耦合性等等。其中一个很重要的环节就是配置管理的问题。

示例

2.常用配置管理解决方案的缺点:

常用的配置管理方案 缺点
硬编码 需要修改代码、繁琐、风险大
写在properties里面 在集群环境下,需要替换和重启
写在xml配置文件中 需要重新打包和重启

3.为什么使用Spring Cloud Config 配置中心?

由于常用的配置管理有很大的缺点,所以spring cloud采用了集中式的配置中心来管理每个服务的配置信息,spring cloud config配置中心,在微服务分布式系统中,采用服务端和客户端来提供可扩展的配置服务,配置中心负责管理所有服务的各种环境配置文件。配置服务中心默认采用Git的方式存储配置文件,因此我们很容易部署修改,有助于对环境配置进行版本管理。

4.Spring Cloud Config 配置中心解决了什么问题?

解决了微服务配置的中心化、版本控制、平台独立、语言独立等问题。

  • Spring Cloud Config的特性:

(1)提供服务端和客户端支持(spring cloud config和spring cloud config client);
(2)集中式管理分布式环境下的应用配置;
(3)基于Spring环境,无缝与Spring应用集成;
(4)可用于任何语言开发的程序;
(5)默认实现基于git仓库,可以进行版本管理。


二、配置中心的简单案例

1.创建配置中心的服务端:

  • 创建项目:


    示例
  • 修改POM文件:

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • 修改配置文件添加Git的地址:
spring.application.name=config-server
server.port=9030

#设置服务注册中心地址
eureka.client.serviceUrl.defaultZone=http://admin:123456@eureka1:8761/eureka/,http://admin:123456@eureka2:8761/eureka/

#Git 配置 
spring.cloud.config.server.git.uri=https://gitee.com/zwzy/config
#Git私有仓库的用户名和密码
#spring.cloud.config.server.git.username=
#spring.cloud.config.server.git.password=
  • 修改启动类:
@EnableConfigServer
@EnableEurekaClient
@SpringBootApplication
public class ConfigServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
  • 创建四个临时配置文件:
    (1)config-client:
e-book=default1.0

(2)config-client-dev:

e-book=devt1.0

(3)config-client-test:

e-book=test1.0

(4)config-client-prod:

e-book=prod1.0
  • 在码云创建一个仓库:


    创建仓库

    示例
  • 将临时配置文件上传到码云仓库:


    示例

    示例
  • 测试启动Config-Server访问配置文件:


    示例

    示例
  • 配置文件的命名规则和访问URL:


    示例

2.创建配置中心的客户端:

  • 创建项目:


    示例
  • 修改POM文件,添加客户端坐标:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
  • 修改配置文件(文件必须为\color{red}{bootstrap.properties}):
spring.application.name=config-client
server.port=9031

#设置服务注册中心地址
eureka.client.serviceUrl.defaultZone=http://admin:123456@eureka1:8761/eureka/,http://admin:123456@eureka2:8761/eureka/

#默认 false,这里设置 true,表示开启读取配置中心的配置
spring.cloud.config.discovery.enabled=true
#对应 eureka 中的配置中心 serviceId,默认是configserver
spring.cloud.config.discovery.serviceId=config-server
#指定环境
spring.cloud.config.profile=dev
#git标签 分支/主干
spring.cloud.config.label=master
  • 修改启动类:
@EnableEurekaClient
@SpringBootApplication
public class ConfigClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }
}
  • 创建Controller测试:
@RestController
public class ConfigClientController {
    
    @Value("${e-book}")
    private String msg;
    
    @RequestMapping("/show")
    public String ShowMsg() {
        return this.msg;
    }
}
示例
  • \color{red}{配置中心的原理}

Config-Client客户端从Config-Server获取配置信息,Config-Server会从Git远程仓库获取最新的配置信息;当Git远程仓库中的配置信息更新后,Config-Server的本地仓库不会立即更新,只有在Config-Client调用Config-Server中的配置时,向Config-Server发送一个post刷新请求,Config-Server才会对本地仓库和远程仓库对比,将远程仓库中的更新内容,更新到本地仓库。

示例

本地仓库

示例

3.在git 端修改配置后,不重启服务如何让客户端生效 :

  • 创建配置中心的客户端:

主要添加actuator坐标,修改配置文件,其他都和上面的客户端一样。

示例
  • 修改POM文件,添加actuator坐标:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
  • 修改配置文件:
#springboot 默认开启了权限拦截 会导致 /refresh 出现 401,拒绝访问 
management.security.enabled=false
  • 修改Controller添加@RefreshScope注解:
@RestController
@RefreshScope//刷新作用域
public class ConfigClientController {
    
    @Value("${e-book}")
    private String msg;
    
    @RequestMapping("/show")
    public String ShowMsg() {
        return this.msg;
    }
}
  • 刷新请求的URL:


    示例
  • 创建发送post请求的URL项目:


    示例
  • 修改POM文件:

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.4</version>
        </dependency>
        <!-- log -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
  • 发送HttpClientUtil工具类:
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状�?是否�?00
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }
    
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
    
    public static void main(String[] args) {
        //修改的内容
        String url ="http://127.0.0.1:9032/refresh";
        String info = HttpClientUtil.doPost(url);
        System.out.println(info);
    }
}
  • 测试:
修改前

修改远程仓库后执行HttpClient工具

修改后
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容