경계의 경계

Spring Cloud Config 사용해보기 본문

Spring Cloud

Spring Cloud Config 사용해보기

gigyesik 2024. 5. 10. 02:50

들어가며

Spring Cloud Config는 다양한 마이크로서비스들의 환경변수를 관리하기 위한 라이브러리이다.

환경변수를 중앙화된 별도의 서비스에서 관리함으로서 마이크로서비스의 코드를 수정하지 않고도 설정이나 환경을 변경할 수 있도록 해준다.

Spring Cloud Config 사용해보기

build.gradle

  • Config Server
dependencies {
    implementation 'org.springframework.cloud:spring-cloud-config-server'
    implementation 'org.springframework.boot:spring-boot-starter-security'
	  implementation 'org.springframework.boot:spring-boot-starter-web'
}
  • Config Client
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.cloud:spring-cloud-starter-config'
}

Config Server 설정

  • @EnableConfigServer 어노테이션 사용하여 Config Server 설정 활성화
@SpringBootApplication
@EnableConfigServer
public class ConfigsampleApplication {

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

}

  • yaml 파일에서 서버 설정 관리
spring:
  application:
    name: configsample
  cloud:
    config:
      server:
        git:
          uri: <https://github.com/gigyesik/developer-roadmap-springboot.git>
          clone-on-start: true
  security:
    user:
      name: gigyesik
      password: 1234

server:
  port: 8888

Config Client 설정

  • API 생성
@SpringBootApplication
@RestController
public class ConfigclientsampleApplication {
	@Value("${user.role}")
	private String role;

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

	@GetMapping(
			value = "/whoami/{username}",
			produces = MediaType.TEXT_PLAIN_VALUE)
	public String whoami(@PathVariable("username") String username) {
		return String.format("Hello! You're %s and you'll become a(n) %s...\\n", username, role);
	}

}
  • application.yaml 에서 Config 서버 설정 불러와 연결하기
spring:
  application:
    name: configclientsample
  profiles:
    active: development
  config:
    import: optional:configserver:<http://gigyesik:1234@localhost:8888>
  • application-development.yaml 로 환경변수 분리
user:
  role: Developer

실행 결과 확인

$ curl <http://localhost:8080/whoami/gigyesik>

// Res
Hello! You're gigyesik and you'll become a(n) Developer...

Resources