Config:分布式中心

SpringCloud Config的作用?

这里写图片描述
1. 为微服务架构提供集中化的外部配置支持;
2. 配置服务器(例如GitHub)为各个不同的微服务应用的所有环境提供了一个中心化的外部配置;
3. 当配置发生变化是时服务不需要重启;
4. 不用环境不用配置,动态配置更新。

组成

config和Eureka一样分为服务端客户端

  1. config server(服务端):也称为分布式配置中心,用来连接配置服务中心为客户端提供获取配置信息。客户端和服务端的交互通过EureKa进行, 服务端也是一个独立微服务应用,注册在EureKa Server中。config Client可以访问EureKa Server中config server获取配置信息。当前服务端的Config Server也可以是可以作用一个可高复用的集群式。
  2. config client:通过指定的配置中心管理配置资源

服务端的配置

1.首先需要创建一个远程的git仓库存放配置信息。
2.新建一个微服务作为服务端
2.1:pom.xml

<!--config server-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!--服务程序需要注册在EureKa注册中心-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2.2:application.yml

spring:
  rabbitmq:
    host: 47.95.13.238 #设置rabbitMQ的客户端的访问端口
  application:
    name: config
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/CampusO2OView/sellerConfig.git #步骤一git仓库地址
          username:  #git用户名
          password:  #密码
          basedir: E:\workspace\IDEA\SellerConfigDir #设置拉取远端git项目后存放的在本地的地址

eureka:
  client:
    service-url:
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ #和EureKa注册进行通信

2.3:主程序添加注解
@EnableConfigServer

@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class SelleConfigApplication {

2.4:测试
127.0.0.1:服务启动端口/XXX.yml

文件格式:
{label}/{name}-{profiles}.yml || /{label}/{name}-{profiles}
name:服务名
profiles:环境
label:分支

服务端的客户度

POM.XML

 <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>

application.yml
注意:在拉取的配置文件如果有连接数据库信息的时候,因为在启动的进行数据库连接,但是连接的配置信息可能会还没从config Server端获取到,那么这时就会出现异常。
解决:把application.yml文件更改为bootstrap.yml ,那么会拉取完配置信息才进行配置文件中的连接数据库等其他操作。

spring:
  application:
    name: order #服务名
  cloud:
    config:
      discovery:
        enabled: true
        service-id: CONFIG #在EureKa服务中心获取的服务应用
      profile: dev #文件名
eureka:
  client:
    service-url:
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ #从这些Eureka集群中获取服务
    register-with-eureka: false   #设置消费者不注册进服务注册中心
  instance:
    prefer-ip-address: true

那么启动config client端的时候,先从EureKa注册中心找到微服务:CONFIG ,然后从该微服务获取:服务名+文件名的配置件(order-yml).

主启动类:不需要添加注解

猜你喜欢

转载自blog.csdn.net/ycd500756/article/details/81005687