(五)Spring Cloud教程——Config(F版本)

参考:方志鹏的专栏

Spring Cloud Config 实现配置中心,看这一篇就够了

1. 简介

Spring Cloud Config 是 Spring Cloud 家族中最早的配置中心,虽然后来又发布了 Consul 可以代替配置中心功能,但是 Config 依然适用于 Spring Cloud 项目,通过简单的配置即可实现功能。

对于一些简单的项目来说,我们一般都是直接把相关配置放在单独的配置文件中,以 properties 或者 yml 的格式出现,更省事的方式是直接放到 application.properties 或 application.yml 中。但是这样的方式有个明显的问题,那就是,当修改了配置之后,必须重启服务,否则配置无法生效。

在 Spring Boot 项目中集成 Spring Cloud Config,可以使用 github 作为配置存储。除了 git 外,还可以用数据库、svn、本地文件等作为存储。下面主要从以下三块来说一下 Config 的使用。

  • 基础版的配置中心(不集成 Eureka);
  • 结合 Eureka 版的配置中心;
  • 实现配置的自动刷新;

2. 基础版

在Spring Cloud Config 组件中,分两个角色,一是Config Server,二是Config Client。下面实现最简单的配置中心,就是启动一个服务作为服务方,之后各个需要获取配置的服务作为客户端来这个服务方获取配置。

2.1 在 github 仓库中增加配置文件

2.2 构建Config Server

创建父工程,pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zang</groupId>
    <artifactId>sc-f-config</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>config-server</module>
        <module>config-client</module>
    </modules>

    <name>sc-f-config</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

创建一个spring-boot项目,取名为config-server,pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zang</groupId>
    <artifactId>config-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>config-server</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.zang</groupId>
        <artifactId>sc-f-config</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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>
</project>

在程序的入口Application类加上@EnableConfigServer注解开启配置服务器的功能:

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);
    }
}

在程序的配置文件application.properties文件配置以下:

spring.application.name=config-server
server.port=8888

spring.cloud.config.server.git.uri=https://github.com/xssdpgy/SpringCloudLearning/
spring.cloud.config.server.git.searchPaths=configCenter
spring.cloud.config.label=master
spring.cloud.config.server.git.username=
spring.cloud.config.server.git.password=
  • spring.cloud.config.server.git.uri:配置git仓库地址
  • spring.cloud.config.server.git.searchPaths:配置仓库路径
  • spring.cloud.config.label:配置仓库的分支
  • spring.cloud.config.server.git.username:访问git仓库的用户名
  • spring.cloud.config.server.git.password:访问git仓库的用户密码

如果Git仓库为公开仓库,可以不填写用户名和密码,如果是私有仓库需要填写,本例子是公开仓库,放心使用。

远程仓库 https://github.com/xssdpgy/SpringCloudLearning/ 中有个文件config-client-dev.properties文件中有一个属性:

foo = 001

启动服务,接下来测试一下。

Spring Cloud Config 有它的一套访问规则,我们通过这套规则在浏览器上直接访问就可以。

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
  • {application} 就是应用名称,对应到配置文件上来,就是配置文件的名称部分,例如上面创建的配置文件。
  • {profile} 就是配置文件的版本,我们的项目有开发版本、测试环境版本、生产环境版本,对应到配置文件上来就是以 application-{profile}.properties加以区分,例如application-dev.properties、application-prod.properties。
  • {label} 表示 git 分支,默认是 master 分支,如果项目是以分支做区分也是可以的,那就可以通过不同的 label 来控制访问不同的配置文件了。

如上,根据第五条规则,拼接地址访问,可以正常返回数据,则说明配置中心服务端一切正常。

2.3 构建config client

创建一个springboot项目,取名为config-client,其pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zang</groupId>
    <artifactId>config-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>config-client</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.zang</groupId>
        <artifactId>sc-f-config</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

其配置文件命名为bootstrap.properties:

spring.application.name=config-client
spring.cloud.config.label=master
spring.cloud.config.profile=dev
spring.cloud.config.uri= http://localhost:8888/
server.port=8881
  • spring.cloud.config.label 指明远程仓库的分支
  • spring.cloud.config.profile
    • dev开发环境配置文件
    • test测试环境
    • pro正式环境
  • spring.cloud.config.uri= http://localhost:8888/ 指明配置服务中心的网址。

程序的入口类,写一个API接口“/hi”,返回从配置中心读取的foo变量的值,代码如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class ConfigClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }

    @Value("${foo}")
    String foo;
    @RequestMapping(value = "/hi")
    public String hi(){
        return foo;
    }
}

打开网址访问:http://localhost:8881/hi,网页显示:

3. 结合 Eureka 版的配置中心

以上讲了 Spring Cloud Config 最基础的用法,但是如果我们的系统中使用了 Eureka 作为服务注册发现中心,那么 Spring Cloud Config 也应该注册到 Eureka 之上,方便其他服务消费者使用,并且可以注册多个配置中心服务端,以实现高可用。

下面对基础版工程进行改造。

3.1 创建Eureka Server

pom.xml文件引入Eureka的起步依赖spring-cloud-starter-netflix- eureka-server。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

在配置文件application.yml上,指定服务端口为8889,加上作为服务注册中心的基本配置:

server:
  port: 8889

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

入口类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

3.2 改造config-server

基于原pom.xml,在其pom.xml文件加上EurekaClient的起步依赖spring-cloud-starter-netflix-eureka-client:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

配置文件application.properties,保持原有配置不变,新增指定服务注册地址为http://localhost:8889/eureka/:

eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/

在 @EnableConfigServer 的基础上增加 @EnableEurekaClient,另外也可以用 @EnableDiscoveryClient 代替 @EnableEurekaClient。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
//@EnableEurekaClient
public class ConfigServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

3.3 改造config-client

基于原pom.xml,在其pom.xml文件加上EurekaClient的起步依赖spring-cloud-starter-netflix-eureka-client:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

配置文件bootstrap.properties,加上服务注册地址为http://localhost:8889/eureka/

spring.application.name=config-client
spring.cloud.config.label=master
spring.cloud.config.profile=dev
#spring.cloud.config.uri= http://localhost:8888/

eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.serviceId=config-server
server.port=8881
  • spring.cloud.config.discovery.enabled 是从配置中心读取文件。
  • spring.cloud.config.discovery.serviceId 配置中心的servieId,即服务名。

在启动类上添加@EnableDiscoveryClient注解,启动即可。

4. Spring Cloud Bus

如果只有一个 client 端的话,那我们用 webhook ,设置手动刷新都不算太费事,但是如果端比较多的话呢,一个一个去手动刷新未免有点复杂。这样的话,我们可以借助 Spring Cloud Bus 的广播功能,让 client 端都订阅配置更新事件,当配置更新时,触发其中一个端的更新事件,Spring Cloud Bus 就把此事件广播到其他订阅端,以此来达到批量更新。

Spring Cloud Bus 核心原理其实就是利用消息队列做广播,所以要先有个消息队列,目前官方支持 RabbitMQ 和 kafka。

4.1 搭建RabbitMQ

这里用的是 RabbitMQ, 所以先要搭一套 RabbitMQ 环境。过程略。

下面对代码进行继续改造。

4.2 改造config-client

在pom文件加上起步依赖spring-cloud-starter-bus-amqp。

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

在配置文件application.properties中加上RabbitMq的配置,包括RabbitMq的地址、端口,用户名、密码。并需要加上spring.cloud.bus的三个配置,具体如下:

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

spring.cloud.bus.enabled=true
spring.cloud.bus.trace.enabled=true
management.endpoints.web.exposure.include=bus-refresh

ConfigClientApplication启动类代码如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
@RefreshScope
public class ConfigClientApplication {

    /**
     * http://localhost:8881/actuator/bus-refresh
     */

    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }

    @Value("${foo}")
    String foo;

    @RequestMapping(value = "/hi")
    public String hi(){
        return foo;
    }
}

依次启动eureka-server、config-server,启动两个config-client,端口为:8881、8882。

访问http://localhost:8881/hi 或者http://localhost:8882/hi 浏览器显示:

4.3 实现配置自动刷新

这时我们去代码仓库改变配置文件foo的值。如果是传统的做法,需要重启服务,才能达到配置文件的更新。此时,我们只需要发送post请求http://localhost:8881/actuator/bus-refresh,你会发现config-client会重新读取配置文件

此时再访问http://localhost:8881/hi 或者http://localhost:8882/hi ,浏览器显示:

另外,/actuator/bus-refresh接口可以指定服务,即使用”destination”参数,比如 “/actuator/bus-refresh?destination=customers:**” 即刷新服务名为customers的所有服务。

题外话:

目前有一些用的比较多的开源的配置中心,比如携程的 Apollo、蚂蚁金服的 disconf 等,对比 Spring Cloud Config,这些配置中心功能更加强大。有兴趣的可以拿来试一试。

原文地址:https://www.cnblogs.com/zjfjava/p/12249034.html

时间: 2024-07-31 13:27:14

(五)Spring Cloud教程——Config(F版本)的相关文章

Spring Cloud Consul 之Greenwich版本全攻略

什么是Consul Consul是HashiCorp公司推出的开源软件,使用GO语言编写,提供了分布式系统的服务注册和发现.配置等功能,这些功能中的每一个都可以根据需要单独使用,也可以一起使用以构建全方位的服务网格.Consul不仅具有服务治理的功能,而且使用分布式一致协议RAFT算法实现,有多数据中心的高可用方案,并且很容易和Spring Cloud等微服务框架集成,使用起来非常的简单,具有简单.易用.可插排等特点.使用简而言之,Consul提供了一种完整的服务网格解决方案 . Consul具

spring cloud Nacos Config配置中心

概述Nacos 是阿里巴巴开源的一个更易于构建云原生应用的动态服务发现.配置管理和服务管理平台.Nacos Config就是一个类似于SpringCloud Config的配置中心接入SpringCloud项目集成Nacos Config配置中心很简单.只需要部署Nacos 客户端并在里面添加配置即可.然后引入Nacos Config动态读取即可1. 创建一个SpringCloud工程cloud-config 修改 pom.xml 文件,引入 Nacos Config Starter 前提得选引

(六)Spring Cloud教程——Sleuth(F版本)

1. 简介 微服务架构上通过业务来划分服务的,通过REST调用,对外暴露的一个接口,可能需要很多个服务协同才能完成这个接口功能,如果链路上任何一个服务出现问题或者网络超时,都会导致接口调用失败.随着业务的不断扩张,服务之间互相调用会越来越复杂.随着服务的越来越多,对调用链的分析会越来越复杂. Spring Cloud Sleuth服务链路跟踪功能就可以帮助我们快速的发现错误根源以及监控分析每条请求链路上的性能等等. 相关术语: Span:基本工作单元,例如,在一个新建的span中发送一个RPC等

(三)Spring Cloud教程——Hystrix(F版本)

参考:方志鹏的专栏 1. Hystrix简介 在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用.为了保证其高可用,单个服务通常会集群部署.由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪.服务与服务之间的依赖性,故障会传播,会对整个微服务

(四)Spring Cloud教程——Zuul(F版本)

参考:方志鹏的专栏 在微服务架构中,需要几个基础的服务治理组件,包括服务注册与发现.服务消费.负载均衡.断路器.智能路由.配置管理等,由这几个基础组件相互协作,共同组建了一个简单的微服务系统.一个简单的微服务系统如下图: 注意:A服务和B服务是可以相互调用的,作图的时候忘记了.并且配置服务也是注册到服务注册中心的. 在Spring Cloud微服务系统中,一种常见的负载均衡方式是,客户端的请求首先经过负载均衡(zuul.Ngnix),再到达服务网关(zuul集群),然后再到具体的服.,服务统一注

(二)Spring Cloud教程——Ribbon 和 Feign(F版本)

参考自:方志朋的专栏 1. Ribbon 1.1 Ribbon简介 Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现.通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用.Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心.配置中心.API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中

Spring Cloud 升级最新 Finchley 版本,踩了所有的坑!

Spring Boot 2.x 已经发布了很久,现在 Spring Cloud 也发布了 基于 Spring Boot 2.x 的 Finchley 版本,现在一起为项目做一次整体框架升级. 升级前 => 升级后 Spring Boot 1.5.x => Spring Boot 2.0.2 Spring Cloud Edgware SR4 => Spring Cloud Finchley.RELEASE Eureka Server Eureka Server 依赖更新 升级前: <

Spring Cloud 教程

Spring Cloud系列教程: Spring Boot + Spring Cloud 构建微服务系统(一):服务注册和发现(Consul) Spring Boot + Spring Cloud 构建微服务系统(二):服务消费和负载(Ribbon) Spring Boot + Spring Cloud 构建微服务系统(三):服务消费和负载(Feign) Spring Boot + Spring Cloud 构建微服务系统(四):容错机制和熔断(Hystrix) Spring Boot + Sp

Spring Cloud之——Config(配置中心)

Spring Cloud Config(配置中心) 大家好,有一段时间没有写技术博客了.由于工作上的事情,这方面很难分配时间.近几年随着服务化的兴起,一批服务化的框架应运而生,像dubbo,thrift,spring-cloud等.在国内使用dubbo的公司非常多,dubbo也是java程序员面试时必备知识点,而且它的官方文档写的非常清晰易懂,这都使得dubbo的普及非常容易.thrift是apache贡献的,似乎也流行了一段时间,小编对这个框架不是很了解.随后spring-cloud一经推出,