将Spring Cloud Config嵌入配置服务器

Spring Cloud Config的基本用法通常是将其分为服务器和客户端使用,但也可以在嵌入模式下启动。

从参考的角度来看,可以考虑使用Spring Cloud Config-嵌入配置服务器。

源代码

plugins {
  id 'org.springframework.boot' version '2.2.6.RELEASE'
  id 'io.spring.dependency-management' version '1.0.9.RELEASE'
  id 'java'
}

sourceCompatibility = '11'
repositories {
  mavenCentral()
}
ext {
  set('springCloudVersion', "Hoxton.SR3")
}
dependencies {
  implementation 'org.springframework.cloud:spring-cloud-config-server'
  implementation 'org.springframework.boot:spring-boot-starter-web'

  testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
  }
}
dependencyManagement {
  imports {
    mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
  }
}
test {
  useJUnitPlatform()
}

服务器端就足够了,网页只是为了进行操作确认。

spring:
  application:
    name: sample
  profiles:
    active: composite
  cloud:
    config:
      server:
        composite:
          - type: native
            search-locations: file:///C:/configtest/
        bootstrap: true
      prefix: config

将配置写入bootstrap.yaml而不是application.yaml中。

以下是用于操作确认的控制器。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@EnableConfigServer
@SpringBootApplication
@RestController
public class Application {
    @Value("${hoge.message}")
    private String message;

    @RequestMapping("/")
    public String home() {
        return "Hello World!" + message;
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args);
    }
}
广告
将在 10 秒后关闭
bannerAds