Loading

配置中心的高可用

在之前的代码中,客户端都是直接调用配置中心的server端来获取配置文件信息。这样就存在了一个问题,客户端和服务端的耦合性太高,如果server端要做集群,客户端只能通过原始的方式来路由,server端改变IP地址的时候,客户端也需要修改配置,不符合springcloud服务治理的理念。springcloud提供了这样的解决方案,我们只需要将server端当做一个服务注册到eureka中,client端去eureka中去获取配置中心server端的服务既可。

服务端改造

(1) 添加依赖

<dependencies>
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-config-server</artifactId>
  </dependency>
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
</dependencies>

(2) 配置文件

eureka:
 client:
   serviceUrl:
     defaultZone: http://localhost:8000/eureka/   ## 注册中心eurka地址
这样server端的改造就完成了。先启动eureka注册中心,在启动server端,在浏览器中访问:http://localhost:8761/ 就会看到server端已经注册了到注册中心了。

服务端改造

(1) 添加依赖 

<dependencies>
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
  </dependency>
  <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.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
  </dependency>
</dependencies>

(2) 配置文件 

  server:
    port: 9002
  eureka:
    client:
      serviceUrl:
        defaultZone: http://127.0.0.1:8761/eureka/
  spring:
    cloud:
      config:
        name: product
        profile: dev
        label: master
        uri: http://localhost:8080
        discovery:
          enabled: true #从eureka中获取配置中心信息
          service-id: config-server

高可用

为了模拟生产集群环境,我们改动server端的端口为1000,再启动一个server端来做服务的负载,提供高可用的server端支持。 

如上图就可发现会有两个server端同时提供配置中心的服务,防止某一台down掉之后影响整个系统的使用。
我们先单独测试服务端,分别访问: http://localhost:10000/product-pro.yml 、http://localhost:10001/product-pro.yml 返回信息: 
  eureka:
    client:
      serviceUrl:
        defaultZone: http://127.0.0.1:8761/eureka/
    instance:
      instance-id: ${spring.cloud.client.ip-address}:9002
      preferIpAddress: true
  productValue: 200
  server:
    port: 9002
  spring:
    application:
      name: shop-service-product
    datasource:
      driver-class-name: com.mysql.jdbc.Driver
      password: 111111
      url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
      username: root
    jpa:
      database: MySQL
      open-in-view: true
      show-sql: true

 

posted @ 2021-07-29 15:56  1640808365  阅读(81)  评论(0编辑  收藏  举报