2.1 Config Server - fanpan26/Fly.SpringCloud GitHub Wiki

新建 Module:fly-config,加入引用

 <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
 </dependency>
添加 @EnableConfigServer 注解

@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class,args);
    }
}
github新建repo作为配置文件的存储地址:https://github.com/fanpan26/spring-cloud-config.git,先上如下传配置文件作为测试

fly-user-service.yml
fly-user-service-dev.yml
fly-user-service-prod.yml
添加配置文件 application.yml

server:
  port: 8000
spring:
  application:
    name: fly-config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/fanpan26/spring-cloud-config.git
          clone-on-start: true

{
	"name": "fly-user-service",
	"profiles": ["dev"],
	"label": "master",
	"version": "c8c3f3058251d54be2726cf8d176343444d10cf5",
	"state": null,
	"propertySources": [{
		"name": "https://github.com/fanpan26/spring-cloud-config.git/fly-user-service-dev.yml",
		"source": {
			"current.profile": "dev"
		}
	}, {
		"name": "https://github.com/fanpan26/spring-cloud-config.git/fly-user-service.yml",
		"source": {
			"current.profile": "zhangsanfeng"
		}
	}]
}
Config Server 端点与配置文件的映射规则如下:

/{application}/{profile}/[{lable}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}/{profile}.properties
/{label}/{application}-{profile}.properties

以上端点都可以映射到{application}-{profile}.properties (yml)这个配置文件。{application}表示微服务的名称,{label}对应Git仓库的分支,默认为master。 访问以下路径,均会有相应的结果

http://localhost:8000/fly-user-service.properties
http://localhost:8000/fly-user-service.yml
http://localhost:8000/fly-user-service-dev.yml
http://localhost:8000/fly-user-service-prod.yml
添加 Config Server 认证,添加引用

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
修改application.yml文件,增加如下配置

spring:
  application:
    name: fly-config-server
  security:
    user:
      name: panzi
      password: 123456
Eureka Server一样,添加认证配置类


@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //开启认证
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}
重新启动 Config Server,访问 http://localhost:8000

img

⚠️ **GitHub.com Fallback** ⚠️