2025. 3. 4. 12:14ㆍSpring Microservice
🎯 Spring Cloud Config와 Spring Boot 클라이언트 통합 정리
Spring Cloud Config를 활용하여 라이선스 서비스(Licensing Service) 의 환경 설정을 중앙에서 관리하고, PostgreSQL을 데이터베이스로 사용하여 라이선스 데이터를 저장하는 방법을 설명합니다.
✅ 1. PostgreSQL을 선택하는 이유
PostgreSQL(이하 Postgres)은 오픈 소스 관계형 데이터베이스 관리 시스템(RDBMS) 중에서 가장 강력한 기능을 제공하는 데이터베이스입니다.
🔥 Postgres의 주요 장점
- 💰 무료 및 오픈소스 → 상업적 라이선스 없이 누구나 사용 가능
- 📊 대용량 데이터 처리 가능 → 쿼리 복잡성을 증가시키지 않고도 대량의 데이터를 효과적으로 처리
- ⚡ MVCC(Multiversion Concurrency Control) 지원
- 트랜잭션별 데이터 상태를 유지하여 읽기 작업이 쓰기 작업을 차단하지 않음
- 🔓 읽기 잠금(Read Lock) 없음
- 트랜잭션 실행 중에도 동시 읽기 가능
- 🔄 핫 스탠바이(Hot Standby) 지원
- 유지보수 중에도 데이터 검색 가능
- 📑 JSON 데이터 타입 지원
- JSON을 네이티브 데이터 타입으로 저장하고 SQL과 함께 쿼리 가능
- 🚀 다양한 프로그래밍 언어 지원
- C, C++, Java, PHP, Python 등과 호환
🎯 2. Spring Cloud Config를 활용한 환경설정 관리
Spring Cloud Config는 애플리케이션의 환경설정을 중앙에서 관리할 수 있도록 도와줍니다.
이를 통해 각 마이크로서비스의 개별 설정을 줄이고, 일관된 설정을 유지할 수 있습니다.
📌 Spring Cloud Config의 동작 방식
1️⃣ 라이선스 서비스(이 블로그의 예제 마이크로서비스 인스턴스)가 시작될 때, 3가지 정보를 Spring Cloud Config Server로 전달
- Spring 프로필 (Spring Profile): 실행 환경(dev, prod 등)
- 애플리케이션 이름 (Application Name):
licensing-service
- Spring Cloud Config 서버의 엔드포인트 (Config Server Endpoint)
2️⃣ 라이선스 서비스가 Spring Cloud Config 서버와 통신하여 설정 정보 요청
- 예:
http://localhost:8071/licensing-service/dev
3️⃣ Config Server는 Git, Vault 등의 저장소에서 설정 정보 조회
- 예:
licensing-service.properties
- 예:
licensing-service-dev.properties
- 예:
licensing-service-prod.properties
4️⃣ Spring Cloud Config Server가 라이선스 서비스로 환경설정 정보를 반환
- 데이터베이스 접속 정보 (
spring.datasource.url
,spring.datasource.username
,spring.datasource.password
등) - Hibernate 설정 (
spring.jpa.hibernate.dialect
,spring.jpa.show-sql
등)
5️⃣ Spring Boot 프레임워크가 해당 값을 애플리케이션에 자동으로 주입
🛠 3. Spring Cloud Config 연동 예제
🔧 1) Config Server 설정
📌 pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
📌 ConfigServerApplication.java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
📌 application.yml
server:
port: 8888
spring:
application:
name: configserver
cloud:
config:
server:
git:
uri: https://github.com/your-repo/config-repo
clone-on-start: true
🔧 2) Licensing Service 설정
📌 pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
📌 bootstrap.yml (Spring Cloud Config 서버 사용 설정)
spring:
application:
name: licensing-service
profiles:
active: dev # 실행 환경을 dev로 설정
cloud:
config:
uri: http://localhost:8888 # Config 서버 주소
fail-fast: true # 설정을 가져오지 못하면 서비스 실행 중지
📌 Git 저장소에 환경설정 파일 추가
licensing-service-dev.properties
spring.jpa.hibernate.ddl-auto=none
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql=true
spring.jpa.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/licensingdb
spring.datasource.username=postgres
spring.datasource.password=postgres
🔧 3) PostgreSQL 연동
📌 License 엔티티
@Entity
@Table(name = "license")
public class License {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String licenseType;
private String organizationId;
private String productName;
// Getters and Setters
}
📌 LicenseRepository
@Repository
public interface LicenseRepository extends JpaRepository<License, Long> {
List<License> findByOrganizationId(String organizationId);
}
📌 LicenseService
@Service
public class LicenseService {
@Autowired
private LicenseRepository licenseRepository;
public List<License> getLicensesByOrg(String organizationId) {
return licenseRepository.findByOrganizationId(organizationId);
}
}
📌 LicenseController
@RestController
@RequestMapping("/v1/organizations/{organizationId}/licenses")
public class LicenseController {
@Autowired
private LicenseService licenseService;
@GetMapping
public List<License> getLicenses(@PathVariable String organizationId) {
return licenseService.getLicensesByOrg(organizationId);
}
}
🚀 4. 실행 및 테스트
1️⃣ Spring Cloud Config 서버 실행
mvn spring-boot:run
2️⃣ Licensing Service 실행
mvn spring-boot:run
3️⃣ PostgreSQL 데이터 확인
SELECT * FROM license;
4️⃣ API 호출 테스트
curl -X GET "http://localhost:8080/v1/organizations/123/licenses"
🎯 5. Summary
1️⃣ Spring Cloud Config를 활용하여 환경설정을 중앙에서 관리하고, PostgreSQL을 사용하여 데이터를 효율적으로 저장 및 관리할 수 있음.
2️⃣ Config Server는 Git, Vault, 파일 시스템 등 다양한 저장소에서 설정을 불러올 수 있어 환경설정을 효율적으로 유지 가능.
3️⃣ 라이선스 서비스가 부팅될 때 Config Server에서 적절한 설정을 가져와 자동으로 주입되므로 운영 환경별(예: dev, prod) 설정을 손쉽게 관리 가능.
👉 이 방식은 마이크로서비스 환경에서 필수적인 중앙 집중식 설정 관리와 확장성 있는 데이터베이스 연동을 가능하게 합니다! 🚀
- Spring Cloud Config 서비스와 라이선싱 서비스 연동 설정
- Spring Cloud Config 서버를 이용한 Data Source 설정
- @ConfigurationProperties를 통한 속성 직접 읽기, Spring Cloud Config 서버를 이용한 속성 새로 고침 및 Git 연동 활용
- Spring Cloud Config 서비스와 Vault 연동을 통한 보안 설정 관리 및 UI 활용
'Spring Microservice' 카테고리의 다른 글
Setting up the configuration files for a service (0) | 2025.03.04 |
---|---|
Spring Cloud Config Server bootstrap 클래스 설정 및 파일 시스템 저장소 구성 (1) | 2025.03.04 |
Building our Spring Cloud Configuration Server (0) | 2025.03.04 |
On managing configuration (0) | 2025.03.04 |
5.Controlling your configuration with the Spring Cloud Configuration Server (0) | 2025.03.04 |