SpringCloud Config高可用的配置中心

高可用的配置中心加上使用Spring Cloud Bus动态刷新配置文件获取

准备

这里需要三个工程Eureka-Server、Config-Server、Config-Client下面依次创建工程


SpringCloud Config高可用的配置中心_第1张图片
b1.png

eureka-server 服务注册发现

创建pom所需要起步依赖包 spring-cloud-starter-netflix-eureka-server



    4.0.0

    com.maven.eureka.server
    eureka-server
    0.0.1-SNAPSHOT
    jar

    eureka-server
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.3.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Finchley.RELEASE
    

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




工程创建完成之后在 EurekaServerApplication上添加注解 @EnableEurekaServer
如下:

  @SpringBootApplication
  @EnableEurekaServer
  public class EurekaServerApplication {

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

application.properties 如下:

server.port=8761
eureka.client.register-with-eureka=false 
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:${server.port}/eureka/

其中 eureka.client.register-with-eureka=false, eureka.client.fetch-registry=false为false表示不注册自己
然后启动 http://localhost:8761

SpringCloud Config高可用的配置中心_第2张图片
b2.png

config-server 配置中心服务端

创建pom所需的起步依赖 spring-cloud-config-server spring-cloud-starter-netflix-eureka-server
pom.xml



    4.0.0

    com.maven.config.server
    config-server
    0.0.1-SNAPSHOT
    jar

    config-server
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.3.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Finchley.RELEASE
    

    
        
            org.springframework.cloud
            spring-cloud-config-server
        

        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




application.yml

spring:
  cloud:
    config:
      server:
        git:
          search-paths: respo # 配置文件所属目录,配置文件不能放在仓库的根目录
          uri: http://IP/liangxiaobo/MyTestSpringcloudConfig.git
          username: *** # 你的用户名
          password: *** # 你的密码
      label: master

  application:
    name: config-server
server:
  port: 8768
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

以上请注册这里用到了git仓库,我用的是自建的git创建服务器,并且是私有(private)项目,需要写用户名(username)和密码(password),config-server做为Eureka的客户端需要向eureka server注册服务,service-url指向http://localhost:8761/eureka/
向git仓库上传一个配置文件 respo/config-client-dev.yml,配置文件不能放在根目录必须放在指定的目录中

foo: foo version 1
name: springcloud-config-server

然后在启动类中加上注解@EnableConfigServer @EnableEurekaClient 代码如下:

@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigServerApplication {

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

这时候想测试config-server的话,要依次启动 eureka-server、config-server
这时候访问 config-server http://localhost:8768/foo/dev


  foo
  
    dev
  
  

这是config-server项目启动时加入的映射

2018-07-25 11:45:58.679  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-25 11:45:58.680  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-25 11:45:58.688  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/encrypt],methods=[POST]}" onto public java.lang.String org.springframework.cloud.config.server.encryption.EncryptionController.encrypt(java.lang.String,org.springframework.http.MediaType)
2018-07-25 11:45:58.689  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/encrypt/{name}/{profiles}],methods=[POST]}" onto public java.lang.String org.springframework.cloud.config.server.encryption.EncryptionController.encrypt(java.lang.String,java.lang.String,java.lang.String,org.springframework.http.MediaType)
2018-07-25 11:45:58.690  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/decrypt/{name}/{profiles}],methods=[POST]}" onto public java.lang.String org.springframework.cloud.config.server.encryption.EncryptionController.decrypt(java.lang.String,java.lang.String,java.lang.String,org.springframework.http.MediaType)
2018-07-25 11:45:58.690  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/decrypt],methods=[POST]}" onto public java.lang.String org.springframework.cloud.config.server.encryption.EncryptionController.decrypt(java.lang.String,org.springframework.http.MediaType)
2018-07-25 11:45:58.690  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/encrypt/status],methods=[GET]}" onto public java.util.Map org.springframework.cloud.config.server.encryption.EncryptionController.status()
2018-07-25 11:45:58.690  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/key],methods=[GET]}" onto public java.lang.String org.springframework.cloud.config.server.encryption.EncryptionController.getPublicKey()
2018-07-25 11:45:58.691  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/key/{name}/{profiles}],methods=[GET]}" onto public java.lang.String org.springframework.cloud.config.server.encryption.EncryptionController.getPublicKey(java.lang.String,java.lang.String)
2018-07-25 11:45:58.695  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}-{profiles}.properties],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.config.server.environment.EnvironmentController.properties(java.lang.String,java.lang.String,boolean) throws java.io.IOException
2018-07-25 11:45:58.696  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}-{profiles}.yml || /{name}-{profiles}.yaml],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.config.server.environment.EnvironmentController.yaml(java.lang.String,java.lang.String,boolean) throws java.lang.Exception
2018-07-25 11:45:58.696  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}/{profiles:.*[^-].*}],methods=[GET]}" onto public org.springframework.cloud.config.environment.Environment org.springframework.cloud.config.server.environment.EnvironmentController.defaultLabel(java.lang.String,java.lang.String)
2018-07-25 11:45:58.696  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{label}/{name}-{profiles}.json],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.config.server.environment.EnvironmentController.labelledJsonProperties(java.lang.String,java.lang.String,java.lang.String,boolean) throws java.lang.Exception
2018-07-25 11:45:58.696  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{label}/{name}-{profiles}.properties],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.config.server.environment.EnvironmentController.labelledProperties(java.lang.String,java.lang.String,java.lang.String,boolean) throws java.io.IOException
2018-07-25 11:45:58.696  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}-{profiles}.json],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.config.server.environment.EnvironmentController.jsonProperties(java.lang.String,java.lang.String,boolean) throws java.lang.Exception
2018-07-25 11:45:58.697  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}/{profiles}/{label:.*}],methods=[GET]}" onto public org.springframework.cloud.config.environment.Environment org.springframework.cloud.config.server.environment.EnvironmentController.labelled(java.lang.String,java.lang.String,java.lang.String)
2018-07-25 11:45:58.697  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{label}/{name}-{profiles}.yml || /{label}/{name}-{profiles}.yaml],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.config.server.environment.EnvironmentController.labelledYaml(java.lang.String,java.lang.String,java.lang.String,boolean) throws java.lang.Exception
2018-07-25 11:45:58.700  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}/{profile}/{label}/**],methods=[GET],produces=[application/octet-stream]}" onto public synchronized byte[] org.springframework.cloud.config.server.resource.ResourceController.binary(java.lang.String,java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest) throws java.io.IOException
2018-07-25 11:45:58.701  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}/{profile}/{label}/**],methods=[GET]}" onto public java.lang.String org.springframework.cloud.config.server.resource.ResourceController.retrieve(java.lang.String,java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest,boolean) throws java.io.IOException
2018-07-25 11:45:58.701  INFO 17912 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{name}/{profile}/**],methods=[GET],params=[useDefaultLabel]}" onto public java.lang.String org.springframework.cloud.config.server.resource.ResourceController.retrieve(java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest,boolean) throws java.io.IOException
2018-07-25 11:45:58.722  INFO 17912 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-25 11:45:58.722  INFO 17912 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

config-client

创建pom所需要的起步依赖 spring-boot-starter-web spring-cloud-starter-config spring-cloud-starter-netflix-eureka-server
pom.xml



    4.0.0

    com.maven.config.client
    config-client
    0.0.1-SNAPSHOT
    jar

    config-client
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.3.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Finchley.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-config
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


启动类中加注释 @RestController @EnableEurekaClient,并在其中增加两个方法读取配置文件中的属性 fooname

@SpringBootApplication
@RestController
@EnableEurekaClient
public class ConfigClientApplication {

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

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

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

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

    @RequestMapping("/name")
    public String getName() {
        return name;
    }
}

在config-client 中增加一个bootstrap.yml,它先于application.yml加载
bootstrap.yml,配置获取application.yml配置文件

spring:
  application:
    name: config-client
  cloud:
    config:
      fail-fast: true 
      discovery:
        enabled: true
        service-id: config-server
  profiles:
    active: dev

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8762

这里的service-id指向config-server项目,config-server集群用service-id起到负载均衡作用,
在获取配置文件 的时候取文件名的方式是 ${spring.application.name}-${profiles.active} 所以这里的文件名是config-client-dev,刚才上传了一个config-client-dev.yml文件到git仓库;
下面启动测试config-client,必须依次启动eureka-server、config-server、config-client,在启动config-client前必须确保config-server已经成功注册到eureka-server
启动成功会在控制台看到

 c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://DESKTOP-L20CIGM:8768/

8768端口是config-server服务器
下面测试访问http://localhost:8762/foo http://localhost:8762/name

SpringCloud Config高可用的配置中心_第3张图片
b3.png

SpringCloud Config高可用的配置中心_第4张图片
b4.png

下面我们再启动一台config-server服务,将端口改为8769 启动
首先看如何一个工程启动多个实例,请看这篇文章:https://blog.csdn.net/forezp/article/details/76408139

server:
  port: 8769

访问http://localhost:8761可以看到config-server有两个分别是8768和8769

b7.png

此时,多次启动config-client会在控制台看到

 c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://DESKTOP-L20CIGM:8768/

 c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://DESKTOP-L20CIGM:8769/

接下来改造工程 加入 spring cloud bus

这里只需要改造 config-client就行,首先在 pom中增加依赖

        
            org.springframework.cloud
            spring-cloud-starter-bus-amqp
        

这里用到了RabbitMQ,所以要先安装RabbitMQ,请自行安装
然后在启动类中加上注释 @RefreshScope

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

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

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

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

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

    @RequestMapping("/name")
    public String getName() {
        return name;
    }
}

然后在application.yml增加mq配置,请注意这是springboot2.0 配置

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: test
    password: root

management:
  endpoints:
    web:
      exposure:
        include: bus-refresh

配置完成,启动测试,将config-client 端口改为8763再启动一台服务,
启动完成后,有两8762和8763两台config-client服务,首先将git上的配置文件内容改为

foo: foo version 2
name: springcloud-config-server2

访问http://localhost:8762/foo http://localhost:8763/foo发现还是 foo version 1
现在需要我们执行post请求 http://localhost:8762/actuator/bus-refresh,用postman 发送post请求成功后

再次访问http://localhost:8762/foo http://localhost:8763/foo
发现两个config-client都是最新的内容

SpringCloud Config高可用的配置中心_第5张图片
b8.png

SpringCloud Config高可用的配置中心_第6张图片
b9.png

为什么只刷新了一个config-client而另一个也获取最新的呢,由于使用了spring cloud bus , 其它实例也会收到刷新配置的消息,也可以用destination参数指向刷新的服务名 "actuator/bus-refresh?destination=config-client:**",config-client的所有实例。

github地址:https://github.com/liangxiaobo/SpringCloudConfigDemo

你可能感兴趣的:(SpringCloud Config高可用的配置中心)