标签: SpringCloudConfig

  • 使用SpringBoot2.1.1配置SpringCloudConfig服务

    配置中心服务器:

    1、在pom.xml中加入如下依赖:

    	        <dependency>
    	        	<groupId>org.springframework.boot</groupId>
    	        	<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    		<!-- Spring Cloud Config - Server依赖 -->
    		<dependency>
    			<groupId>org.springframework.cloud</groupId>
    			<artifactId>spring-cloud-config-server</artifactId>
    			<version>2.1.1.RELEASE</version>
    		</dependency>

    注意高亮行,这个version需要和springboot的版本号一致。

    2、在启动类中加入@EnableConfigServer注解

    3、创建bootstrap.yml配置文件,本地配置如下:

    #服务启动端口配置:
    server:  
      port: 3000
      
    #指定配置文件所在目录或地址
    spring:
      profiles:
        active: native
      cloud:
        config:
          server:
            native:
              search-locations: classpath:/config/
              #search-locations: D:/Workspaces/zero4j/config/src/main/resources/config

    4、在项目的resources(class)目录中创建config文件夹,并在里面新增application-dev.properties文件,内容如下:

    server.address=127.0.0.1
    server.port=8081
    a.url=dev1233

    5、启动并访问 http://localhost:3000/application-dev.properties,能看到

    配置客户端:

    1、在pom.xml中加入如下依赖:

    		<dependency>
                		<groupId>org.springframework.boot</groupId>
                		<artifactId>spring-boot-starter-web</artifactId>
            	</dependency>
    
    		<!-- Spring Cloud Config - Client依赖 -->
    		<dependency>
    			<groupId>org.springframework.cloud</groupId>
    			<artifactId>spring-cloud-config-client</artifactId>
    			<version>2.1.1.RELEASE</version>
    		</dependency>

    同样的,version那里切记要跟springboot的版本一致。

    2、创建bootstrap.yml配置文件,配置如下:

    #启动端口配置:
    server:  
      port: 8080
    
    # 指明配置服务中心的网址
    spring:
      application:
        name: application
      cloud:
        config:
          label: master
          profile: dev
          uri: http://127.0.0.1:3000

    3、创建测试用的controller

    package com.zero4j.controller;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestController {
    
    	@Value("${a.url}")
    	private String datUrl;
    	
    	@GetMapping(value = "/test")
    	public String hi(){
    		return datUrl;
    	}
    
    }
    

    4、启动并访问http://localhost:8081/test,便能看到client获取server的class中config里的配置文件对应的a.url配置