Spring cloud系列三 Spring Cloud 配置中心集群

本是古典 何须时尚 2021-09-14 05:18 444阅读 0赞

1. 概述

上篇文章Spring cloud系列二 Spring Cloud 配置中心的基本用法我们介绍了配置中心的基本用法,但是这个用法有个缺点,只有一台配置服务。如果这台服务挂掉,则整个服务不可用。为了提高配置中心的可靠性,本节我们介绍将配置中心注册成服务,客户端通过注册中心获取服务。这样可以保证有多台服务可以提供服务,如果一台服务出问题,则客户端自动访问另一台服务

本节,我们只重点讲集群相关的配置,基本的配置中心配置本节略,如果你有兴趣可以看上篇内容

2. 配置中心集群和使用

2.1. 配置中心集群

配置中心集群主要通过将配置服务注册成服务来达到集群的目地。

配置中心工程: cloud-config-center
配置中心的其它配置见上篇文章内容,这里只介绍注册成服务的部分

  • @EnableEurekaClient:通过本注解将配置中心注册到配置中心

    @SpringBootApplication
    @EnableConfigServer // 激活该应用为配置文件服务器:读取远程配置文件,转换为rest接口服务
    @EnableEurekaClient // 配置本应用将使用服务注册和服务发现
    public class CloudGitConfigServerApplication {

    1. public static void main(String[] args) {
    2. args = new String[1];
    3. args[0] = "--spring.profiles.active=gitsimple2";
    4. SpringApplication.run(CloudGitConfigServerApplication.class, args);
    5. }

    }

application-gitsimple2.yml:部分相关配置内容如下

  • spring.application.name:配置服务的服务名称

    spring:
    application:

    1. name: config-config-gitsimple2

2.2. 客户端访问配置中心集群

工程名称:cloud-service
bootstrap-simple2.yml:部分相关配置内容如下

  • 注释掉’spring.cloud.config.uri’的配置,增加两个新的配置值:
  1. * spring.cloud.config.discovery.enabled:如果设置为true,则表示通过注册中心获取配置服务中心地址
  2. * spring.cloud.config.discovery.service-id:配置中心的服务注册名称,即配置中心工程cloud-config-centerapplication.ymlspring.application.name的值
  3. spring:
  4. cloud:
  5. # 配置服务器的地址
  6. config:
  7. # uri: http://127.0.0.1:10888
  8. # 通过注册服务
  9. discovery:
  10. enabled: true
  11. service-id: config-config-gitsimple2
  12. # 要读取配置文件读取的值
  13. name: cloud-config
  14. # 如果不设置此值,则系统设置此值为 spring.profiles.active
  15. profile: dev

2.3. 测试

依次启动工程:
cloud-registration-center、 cloud-config-center、cloud-service

查看当前的注册到配置中的信息
http://127.0.0.1:10761/
这里写图片描述

访问url: http://127.0.0.1:10082/simple,返回内容:

  1. {"age":112,"name":"git2-default-dev","randomNum":73}

说明我们的配置已经生效了

4. 代码

以上的详细的代码见下面
github代码,请使用tag v0.3,不要使用master

发表评论

表情:
评论列表 (有 0 条评论,444人围观)

还没有评论,来说两句吧...

相关阅读