2025. 3. 7. 17:06ㆍSpring Microservice
🛠️ Spring Cloud Config Server를 사용한 데이터 소스 설정
현재까지는 데이터베이스 설정 정보가 마이크로서비스에 직접 주입되어 있습니다. 이제 Postgres 데이터베이스와의 연결을 위해 라이선싱 마이크로서비스(Licensing Microservice)를 설정하고, 이를 리팩토링하여 각 클래스가 별도의 역할을 담당하도록 분리해야 합니다.
📂 라이선싱 서비스 구조
📌 클래스명 | 📍 위치 |
---|---|
📝 License |
com.optimagrowth.license.model |
🏛️ LicenseRepository |
com.optimagrowth.license.repository |
⚙️ LicenseService |
com.optimagrowth.license.service |
📝 License 엔터티 클래스
라이선싱 데이터를 저장하는 JPA 엔터티 클래스입니다.
package com.optimagrowth.license.model;
import javax.persistence.*;
import org.springframework.hateoas.RepresentationModel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter @Setter @ToString
@Entity
@Table(name="licenses")
public class License {
@Id
@Column(name = "license_id", nullable = false)
private String licenseId;
private String description;
@Column(name = "organization_id", nullable = false)
private String organizationId;
@Column(name = "product_name", nullable = false)
private String productName;
@Column(name = "license_type", nullable = false)
private String licenseType;
@Column(name="comment")
private String comment;
public License withComment(String comment){
this.setComment(comment);
return this;
}
}
🔹 JPA 어노테이션 설명
@Entity
: JPA 엔터티로 지정@Table(name="licenses")
: DB의 "licenses" 테이블과 매핑@Id
: 기본 키(Primary Key) 설정@Column(name="organization_id")
: DB의 컬럼명과 매핑 (이름이 같으면 생략 가능)
📌 TIP
속성과 DB 컬럼명이 같으면 @Column 생략 가능!
🏛️ LicenseRepository (Spring Data JPA)
데이터베이스와의 연결을 담당하는 Spring Data JPA Repository입니다.
package com.optimagrowth.license.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.optimagrowth.license.model.License;
@Repository
public interface LicenseRepository extends CrudRepository<License, String> {
List<License> findByOrganizationId(String organizationId);
License findByOrganizationIdAndLicenseId(String organizationId, String licenseId);
}
🔹 Spring Data JPA 기능
CrudRepository<License, String>
: 기본 CRUD 메서드 제공@Repository
: Spring이 Repository로 인식(@Repository 어노테이션은 @Componet 어노테이션을 메타어노테이션으로 가지고 있는 스테레오타입의 어노테이션)- 쿼리 메서드 사용 가능 (Spring이 자동으로 SQL 변환)
📌 Spring Data JPA 주요 메서드
📌 메서드명 | 🔍 설명 |
---|---|
count() |
총 개수 반환 |
delete(entity) |
특정 엔터티 삭제 |
deleteAll() |
모든 엔터티 삭제 |
findById(id) |
특정 ID로 엔터티 조회 |
findAll() |
모든 엔터티 조회 |
save(entity) |
엔터티 저장/업데이트 |
📌 Custom Query 메서드 예시
List<License> findByOrganizationId(String organizationId);
License findByOrganizationIdAndLicenseId(String organizationId, String licenseId);
➡ Spring이 자동으로 SQL을 생성하여 실행!
⚙️ LicenseService (비즈니스 로직)
비즈니스 로직을 담당하는 서비스 클래스입니다.
package com.optimagrowth.license.service;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import com.optimagrowth.license.model.License;
import com.optimagrowth.license.repository.LicenseRepository;
import com.optimagrowth.license.config.ServiceConfig;
@Service
public class LicenseService {
@Autowired
MessageSource messages;
@Autowired
private LicenseRepository licenseRepository;
@Autowired
ServiceConfig config;
public License getLicense(String licenseId, String organizationId){
License license = licenseRepository.findByOrganizationIdAndLicenseId(organizationId, licenseId);
if (license == null) {
throw new IllegalArgumentException(
String.format(messages.getMessage("license.search.error.message", null, null),
licenseId, organizationId));
}
return license.withComment(config.getProperty());
}
public License createLicense(License license){
license.setLicenseId(UUID.randomUUID().toString());
licenseRepository.save(license);
return license.withComment(config.getProperty());
}
public License updateLicense(License license){
licenseRepository.save(license);
return license.withComment(config.getProperty());
}
public String deleteLicense(String licenseId){
License license = new License();
license.setLicenseId(licenseId);
licenseRepository.delete(license);
return String.format(messages.getMessage("license.delete.message", null, null), licenseId);
}
}
🔹 주요 역할
@Service
: Spring 서비스 컴포넌트로 등록@Autowired LicenseRepository
: 데이터 저장/조회getLicense()
: 라이선스 조회createLicense()
: 새 라이선스 생성 (UUID
사용)updateLicense()
: 라이선스 업데이트deleteLicense()
: 라이선스 삭제
🏗️ Spring Bean 간의 의존 관계
각 클래스 간의 연결은 Spring의 @Autowired 어노테이션을 통해 자동 주입됩니다.
graph TD
A[LicenseController] -->|의존성 주입| B[LicenseService]
B -->|의존성 주입| C[LicenseRepository]
C -->|DB 접근| D[Postgres Database]
✔ 컨트롤러 → 서비스 → 리포지토리 → DB 순서로 동작
✔ Spring이 각 Bean을 자동으로 주입(@Autowired)
🚀 이제 Spring Cloud Config Server를 활용하여 데이터베이스 정보를 외부 설정 파일에서 관리할 수 있습니다. 이를 통해 마이크로서비스 아키텍처에서 설정을 중앙에서 관리할 수 있으며, 코드 수정 없이 환경을 변경할 수 있습니다!
다음 단계에서는 Spring Cloud Config Server를 사용하여 설정을 외부에서 관리하는 방법을 살펴보겠습니다! 🚀
'Spring Microservice' 카테고리의 다른 글
Spring Cloud Config 서비스와 Vault 연동을 통한 보안 설정 관리 및 UI 활용 (0) | 2025.03.09 |
---|---|
@ConfigurationProperties를 통한 속성 직접 읽기, Spring Cloud Config 서버를 이용한 속성 새로 고침 및 Git 연동 활용 (0) | 2025.03.09 |
Spring Cloud Config 서비스와 라이선싱 서비스 연동 설정 (0) | 2025.03.07 |
Setting up the configuration files for a service (0) | 2025.03.04 |
Spring Cloud Config Server bootstrap 클래스 설정 및 파일 시스템 저장소 구성 (1) | 2025.03.04 |