반응형
본 내용은 인프런의 이도원 님의 강의 "Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)" 내용을 바탕으로 정리한 내용입니다.
Spring Cloud Config란?
- 분산 시스템에서 애플리케이션의 설정을 중앙 집중화하여 관리할 수 있는 도구
- 서버, 클라이언트 구성에 필요한 설정 정보(application.yml)를 외부에서 변경하고, 설정의 버전을 추적할 수 있다.
- 각 서비스를 다시 빌드하지 않고 적용이 가능하다.
- 애플리케이션 배포 파이프라인을 통해 DEV / UAT / PROD 환경에 맞는 구성정보를 사용한다.
- Config Server: 설정 파일을 저장하고 애플리케이션에 제공.
- Config Client: 서버에서 설정 정보를 가져와 애플리케이션에 적용.
Local Git Repository
# 깃 디렉토리 생성
cd C:\MSA\git-local-lepo
# 깃 저장소 초기화
git init
# yml 파일 생성
code ecommerce.yml
# 설정 파일을 스테이징에 추가
git add ecommerce.yml
git config user.email "tmdwn752@naver.com"
# 깃 메시지 업데이트
git commit -m "upload a default application yaml file"
- 로컬 또는 원격 Git 저장소 생성.
ecommerce.yml
token:
expiration_time: 864000000
secret: YourSuperSecretKeyForJwtHS512AlgorithmYourSuperSecretKeyForJwtHS512Algorithm
gateway:
ip: 127.0.0.1
ConfigService 프로젝트 생성
- Spring Boot : 3.2.6
- Java : 17
- Project Name : ConfigService
- Dependencies : ConfigServer
application.yml
server:
port: 8888
spring:
application:
name: ConfigService
cloud:
config:
server:
git:
uri: file://C:\MSA\git-local-lepo
- Git 저장소 경로를 application.yml 에 설정
ConfigServiceApplication
package com.example.ConfigService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServiceApplication.class, args);
}
}
- @EnableConfigServer 어노테이션으로 Config Server 활성화
ConfigSerivce 기동
{
"name": "ecommerce",
"profiles": [
"default"
],
"label": null,
"version": "08c0cbc24f44b1a472f90a7eab24790c48b7526c",
"state": null,
"propertySources": [
{
"name": "file://C:\\MSA\\git-local-lepo/ecommerce.yml",
"source": {
"token.expiration_time": 864000000,
"token.secret": "YourSuperSecretKeyForJwtHS512AlgorithmYourSuperSecretKeyForJwtHS512Algorithm",
"gateway.ip": "192.168.0.8"
}
}
]
}
- http://localhost:8888/ecommerce/default 호출시 application.yml 파일의 설정을 읽어온다.
UserService 프로젝트
- 서버에서 Config 설정 정보를 가져와 애플리케이션에 적용.
application.yml
#token:
# expiration_time: 864000000
# secret: YourSuperSecretKeyForJwtHS512AlgorithmYourSuperSecretKeyForJwtHS512Algorithm
- JWT 토큰 정보는 ConfigService에서 읽어올거라 주석처리
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
- Dependencies 추가
bootstrap.yml
spring:
cloud:
config:
uri: http://127.0.0.1:8888 # 이 주소로 Config 서버에 접근
name: ecommerce # Config 설정파일 이름
- ConfigService에서 설정 정보를 가져오기 위한 설정
UserController
private Environment env;
@Autowired
public UserController(UserService userService, Environment env){
this.userService = userService;
this.env = env;
}
@GetMapping("/health_check")
public String status(){
// 랜덤으로 설정된 서버 포트를 알려준다.
return String.format("It's Working in User Service"
+ ", port(local.sever.port)=" + env.getProperty("local.server.port")
+ ", port(sever.port)=" + env.getProperty("server.port")
+ ", with token secret" + env.getProperty("token.secret")
+ ", with token time" + env.getProperty("token.expiration_time"));
}
- status() 수정하여 ecommerce.yml 파일의 설정정보를 가져와 출력한다.
UserService 프로젝트 기동
- 127.0.0.1:랜덤포트/health_check 호출하여 서버 정보 출력
Spring Boot Actuator
- Spring Boot 애플리케이션의 운영 정보와 모니터링 기능을 제공하는 라이브러리이다.
- Metric 수집을 위한 Http End point를 제공한다.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- spring-boot-starter-actuator 의존성 추가하여 Actuator 활성화
WebSecurityConfig
/**
* 요청에 대한 인증 처리
* 특정 ip이외에서 접속할 경우 모든 요청은 인증이 필요하다.
* @param http
* @return
* @throws Exception
*/@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/actuator").permitAll()
.requestMatchers("/**").access(this::hasIpAddress)// 여기에 특정 IP 주소를 지정
.anyRequest().authenticated()
)
.addFilter(getAuthenticationFilter()) // getAuthenticationFilter() 메서드를 구현해야 합니다.
.csrf(CsrfConfigurer::disable); // CSRF 보호 비활성화
return http.build();
}
- /actuator url로 접근 시 권한 없이 접속 허용할 수 있도록 변경
application.yml 추가
management:
endpoints:
web:
exposure:
include: refresh, health, beans
#token:
# expiration_time: 864000000
# secret: YourSuperSecretKeyForJwtHS512AlgorithmYourSuperSecretKeyForJwtHS512Algorithm
- 현재 ConfigService에서 가져오는 정보를 refresh 한다.
- 토큰 정보는 외부에서 가져오기 때문에 주석처리한다.
git add > git commit > http://127.0.0.1:랜덤포트/refresh 호출시 ConfigService 설정을 변경 하고 실시간으로 반영할 수 있다.
GatewatService 수정
pom.xml 수정
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- dependency 추가
bootstrap.yml 생성
spring:
cloud:
config:
uri: http://127.0.0.1:8888
name: ecommerce
application.yml 추가
- id: UserService
uri: lb://UserService
predicates:
- Path=/userService/actuator/**
- Method=GET,POST
filters:
- RemoveRequestHeader=Cookie
- RewritePath=/userService/(?<segment>.*), /$\{segment} # /userService 패턴이 들어오면 제거해서 호출
management:
endpoints:
web:
exposure:
include: refresh, health, beans, httpexchanges
#token:
# expiration_time: 864000000
# secret: YourSuperSecretKeyForJwtHS512AlgorithmYourSuperSecretKeyForJwtHS512Algorithm
- 특정 엔드 포인트를 활성하여 웹을 통해 접근할 수 있게 한다.
- 토큰 정보는 외부에서 가져오기 때문에 주석처리한다.
GatewayServiceApplication 수정
package com.example.GatewayService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository;
import org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class GatewayServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServiceApplication.class, args);
}
/**
* HTTP 교환 기록을 활성화하는 설정
* @return
*/
@Bean
public HttpExchangeRepository httpExchangeRepository(){
return new InMemoryHttpExchangeRepository();
}
}
- 메모리에 HTTP 교환정보를 저장하는 httpExchangeRepository()를 생성한다.
결과
- postman 으로 http://127.0.0.1:8080/userService/login 호출 시 정상적으로 로그인 된다.
- ConfigService의 refresh를 통해 공통 프로퍼티를 변경할 수 있다.
- /actuator/refresh 호출로 변경된 설정을 애플리케이션에 반영 가능.
Multiple environments
- 개발, 테스트, 운영 등 다양한 환경에 맞는 설정을 관리하기 위해 여러 property 파일을 사용한다.
- 여기서는 ecommerce, ecommerce-dev, ecommerce-prod 3가지 파일을 사용한다.ecommerce-dev.yml
token:
expiration_time: 864000000
secret: YourSuperSecretKeyForJwtHS256AlgorithmDev
gateway:
ip: 127.0.0.1
- 개발 환경에 맞는 설정 요청
ecommerce-prod.yml
token:
expiration_time: 864000000
secret: YourSuperSecretKeyForJwtHS256AlgorithmProd
gateway:
ip: 127.0.0.1
- 운영 환경에 맞는 설정 요청
Remote Git Repository
- 우선 깃허브 사이트에서 깃 레포지토리를 새로 생성한다. ex) SpingCouldConfig
git commit
PS C:\MSA\git-local-lepo> git add .
PS C:\MSA\git-local-lepo> git commit -m "changed the yaml file"
# 깃 레포지토리와 로컬 디렉토리 연결
git remote add orgin https://github.com/tmdwn725/SpringCloudConfig.git
# 연결된 깃 확인
git reomte -v
# 깃 레포지토리의 orgin과 master로 동기화하여 push 한다.
git push --set-upstream orgin master
- Git 저장소 생성
- 깃허브에서
SpringCloudConfig
라는 원격 저장소를 생성한다.
- 깃허브에서
- Git 커밋 및 푸시
- 로컬 저장소와 원격 Git 저장소를 연결하고 설정 파일을 푸시한다.
ConfigService 수정
application.yml
server:
port: 8888
spring:
application:
name: ConfigService
cloud:
config:
server:
git:
uri: https://github.com/tmdwn725/SpringCloudConfig
# uri: file://C:\MSA\git-local-lepo
- Config 서버가 Git 저장소의 설정 파일을 읽어오도록
application.yml
을 수정
결과
요청
- Spring Cloud Config 서버 실행 후, 브라우저 또는 Postman으로 아래 URL을 호출하여 설정 파일을 확인
응답
{
"name": "ecommerce",
"profiles": [
"dev"
],
"label": null,
"version": "4db6b279dd2ff56550a8536f0473bfde741c9f8f",
"state": null,
"propertySources": [
{
"name": "file://C:\\MSA\\git-local-lepo/ecommerce-dev.yml",
"source": {
"token.expiration_time": 864000000,
"token.secret": "YourSuperSecretKeyForJwtHS256AlgorithmDev",
"gateway.ip": "127.0.0.1"
}
},
{
"name": "file://C:\\MSA\\git-local-lepo/ecommerce.yml",
"source": {
"token.expiration_time": 864000000,
"token.secret": "YourSuperSecretKeyForJwtHS256Algorithm",
"gateway.ip": "127.0.0.1"
}
}
]
- http://127.0.0.1:8888/ecommerce/dev 호출 시 설정 정보를 잘 가져오는 것을 확인할 수 있다.
- ecommerce-dev.yml의 설정값이 응답에 포함되며, 이를 통해 개발 환경 설정이 잘 적용되었음을 알 수 있다.
- 동적 환경 관리: 필요 시 프로파일 이름(dev, prod)을 변경하여 다른 환경 설정 정보를 호출할 수 있다.
Native File Repository
- application.yml 파일의 특정 폴더 경로를 설정하여 해당 폴더의 yml 설정 파일을 읽어와 유동적으로 설정 정보를 사용할 수 있다.
설정 파일 추가
- C:/MSA/native-file-lepo 로컬 디렉토리에 설정 파일 추가config.yml
token:
expiration_time: 864
secret: YourConfigSuperSecretKeyForJwtHS256Algorithm
gateway:
ip: 127.0.0.1
user.yml
token:
expiration_time: 864
secret: YourUserSuperSecretKeyForJwtHS256Algorithm
gateway:
ip: 127.0.0.1
ConfigService 수정
application.yml
server:
port: 8888
spring:
application:
name: ConfigService
profiles:
active: native
cloud:
config:
server:
native:
search-locations: file:///C:\MSA\native-file-lepo
git:
uri: https://github.com/tmdwn725/SpringCloudConfig
# uri: file://C:\MSA\git-local-lepo
- native-file-lepo 폴더 하위 설정 파일 읽어오도록 수정
- spring.profiles.active: native를 설정하여 Native 모드를 활성화한다.
- spring.cloud.config.server.native.search-locations에 로컬 디렉토리 경로(C:/MSA/native-file-lepo)를 지정한다.
결과
요청
- Config 서버를 실행한 후 브라우저나 Postman으로 설정 파일을 요청하여 확인한다.
- URL 호출
- config.yml:
http://127.0.0.1:8888/config/native
- user.yml:
http://127.0.0.1:8888/user/native
- config.yml:
응답
{
"name": "config",
"profiles": [
"native"
],
"label": null,
"version": null,
"state": null,
"propertySources": [
{
"name": "file:/C:/MSA/native-file-lepo/config.yml",
"source": {
"token.expiration_time": 864,
"token.secret": "YourConfigSuperSecretKeyForJwtHS256Algorithm",
"gateway.ip": "127.0.0.1"
}
}
]
}
- Config 서버의 application.yml 파일을 수정하여 Native File Repository를 활성화
- http://127.0.0.1:8888/config/native 호출 시 ConfigService가 config.xml 파일 설정정보를 json 형식으로 가져온다.
반응형
'Cloud > MSA' 카테고리의 다른 글
[MSA] Java KeyStore(JKS) (0) | 2024.12.02 |
---|---|
[MSA] Spring Cloud Bus (0) | 2024.12.02 |
[MSA] MicroService 구현(로그인) (0) | 2024.11.27 |
[MSA] MicroService 구현(주문 서비스) (1) | 2024.11.27 |
[MSA] MicroService 구현(상품 서비스) (0) | 2024.11.27 |