Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
94d20ff
chore(config) : 테스트 시 Config Server 로드 비활성화를 위해 optional:configserver…
hellonaeunkim Feb 13, 2026
5f29430
test(config): 테스트 yml에 .env import 추가 및 Config/Eureka 비활성화 설정 적용
hellonaeunkim Feb 13, 2026
fa67b13
test: Product 도메인 테스트 편의성을 위한 Fixture 클래스 추가
hellonaeunkim Feb 13, 2026
13cfe95
test: Stock 도메인 테스트 편의성을 위한 Fixture 클래스 추가
hellonaeunkim Feb 13, 2026
cd1478c
test(stock): StockServiceImpl 재고 감소 통합 테스트 추가
hellonaeunkim Feb 13, 2026
2cf5cf2
feat(stock) : Redisson 의존성 및 Redis 설정 추가
hellonaeunkim Jun 1, 2026
5098711
feat(stock) : RedissonClient 설정 추가
hellonaeunkim Jun 1, 2026
1361009
feat(stock): 재고 감소 락 인터페이스 추가
hellonaeunkim Jun 2, 2026
09b243f
feat(stock): Redisson 분산 락 구현체 추가
hellonaeunkim Jun 3, 2026
ab1fff5
test(stock) : 재고 감소 동시 요청 테스트 추가
hellonaeunkim Jun 16, 2026
c6343cb
feat(stock): 재고 감소 트랜잭션 분리로 락 해제 순서 개선
hellonaeunkim Jun 16, 2026
07a2889
feat(stock): 락 획득 실패 시 제한적 재시도 적용
hellonaeunkim Jun 16, 2026
0578fca
test(stock) : 테스트용 Redis yml 추가
hellonaeunkim Jun 16, 2026
71ac6e2
chore : 코드 포맷팅(spotlessApply) 적용
hellonaeunkim Jun 16, 2026
f9d1498
fix : Docker 환경의 Redis 설정 변수명 일치
hellonaeunkim Jun 17, 2026
2921668
fix : prod 및 test 환경별 Config Server 연결 설정
hellonaeunkim Jun 17, 2026
b803d7f
chore : 코드 포맷팅(spotlessApply) 적용
hellonaeunkim Jun 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion config/src/main/resources/config-repo/product-service.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ spring:
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
driver-class-name: com.mysql.cj.jdbc.Driver
data:
redis:
host: ${SPRING_DATA_REDIS_HOST:localhost}
port: ${SPRING_DATA_REDIS_PORT:6379}

jpa:
hibernate:
Expand All @@ -25,4 +29,4 @@ management:
endpoint: "http://localhost:9411/api/v2/spans"
tracing:
sampling:
probability: 1.0
probability: 1.0
6 changes: 3 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ services:
networks:
- hubeleven-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8761/actuator/health"]
test: [ "CMD", "curl", "-f", "http://localhost:8761/actuator/health" ]
interval: 10s
timeout: 5s
retries: 5
Expand Down Expand Up @@ -103,8 +103,8 @@ services:
- SPRING_DATASOURCE_PASSWORD=${SPRING_DATASOURCE_PASSWORD}
- SPRING_JPA_DATABASE_PLATFORM=org.hibernate.dialect.MySQL8Dialect
- SPRING_JPA_HIBERNATE_DDL_AUTO=update
- SPRING_REDIS_HOST=${REDIS_HOST}
- SPRING_REDIS_PORT=${REDIS_PORT}
- SPRING_DATA_REDIS_HOST=${REDIS_HOST}
- SPRING_DATA_REDIS_PORT=${REDIS_PORT}
- MANAGEMENT_ZIPKIN_TRACING_ENDPOINT=${ZIPKIN_ENDPOINT}
depends_on:
- eurekaServer
Expand Down
3 changes: 3 additions & 0 deletions product/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

// Redis / Redisson
implementation 'org.redisson:redisson:3.27.2'

// External Libraries
implementation 'com.github.ElevenHub:HubEleven-common:v0.0.1'

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.hubEleven.stock.application.port;

import java.util.function.Supplier;

public interface StockLockManager {

<T> T executeWithLock(String lockKey, Supplier<T> supplier);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.hubEleven.stock.application.service;

import static com.hubEleven.product.domain.exception.ProductErrorCode.PRODUCT_NOT_FOUND;
import static com.hubEleven.stock.domain.exception.StockErrorCode.STOCK_NOT_FOUND;

import com.commonLib.common.exception.GlobalException;
import com.hubEleven.product.domain.model.Product;
import com.hubEleven.product.domain.repository.ProductRepository;
import com.hubEleven.stock.application.dto.StockResult;
import com.hubEleven.stock.domain.model.Stock;
import com.hubEleven.stock.domain.repository.StockRepository;
import com.hubEleven.stock.presentation.dto.request.StockRequests;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RequiredArgsConstructor
public class StockDecreaseProcessor {

private final StockRepository stockRepository;
private final ProductRepository productRepository;

@Transactional
public StockResult decrease(StockRequests.Decrease request) {
Product product =
productRepository
.findByIdNotDeleted(request.productId())
.orElseThrow(() -> new GlobalException(PRODUCT_NOT_FOUND));

Stock stock =
stockRepository
.findByProductId(request.productId())
.orElseThrow(() -> new GlobalException(STOCK_NOT_FOUND));

stock.decreaseQuantity(request.quantity());

return StockResult.from(stock, product.getName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.hubEleven.product.domain.model.Product;
import com.hubEleven.product.domain.repository.ProductRepository;
import com.hubEleven.stock.application.dto.StockResult;
import com.hubEleven.stock.application.port.StockLockManager;
import com.hubEleven.stock.domain.model.Stock;
import com.hubEleven.stock.domain.repository.StockRepository;
import com.hubEleven.stock.presentation.dto.request.StockRequests;
Expand All @@ -21,6 +22,8 @@ public class StockServiceImpl implements StockService {

private final StockRepository stockRepository;
private final ProductRepository productRepository;
private final StockLockManager stockLockManager;
private final StockDecreaseProcessor stockDecreaseProcessor;

private Product getProductOrThrow(UUID productId) {
return productRepository
Expand Down Expand Up @@ -60,16 +63,9 @@ public StockResult getStockByProductId(UUID productId) {
}

@Override
@Transactional
public StockResult decreaseStock(StockRequests.Decrease request) {

Product product = getProductOrThrow(request.productId());

Stock stock = getStockOrThrow(request.productId());

stock.decreaseQuantity(request.quantity());

return StockResult.from(stock, product.getName());
return stockLockManager.executeWithLock(
"stock:decrease:" + request.productId(), () -> stockDecreaseProcessor.decrease(request));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum StockErrorCode implements ErrorCode {
DECREASE_QUANTITY_INVALID(HttpStatus.BAD_REQUEST, "재고 감소 수량은 1 이상이어야 합니다."),
RESTORE_QUANTITY_INVALID(HttpStatus.BAD_REQUEST, "재고 복원 수량은 1 이상이어야 합니다."),
INSUFFICIENT_STOCK(HttpStatus.BAD_REQUEST, "재고가 부족합니다."),
STOCK_LOCK_TIMEOUT(HttpStatus.CONFLICT, "재고 감소 요청이 많아 잠시 후 다시 시도해 주세요."),
INITIAL_QUANTITY_INVALID(HttpStatus.BAD_REQUEST, "초기 재고 수량은 0 이상이어야 합니다.");

private final HttpStatus httpStatus;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.hubEleven.stock.infrastructure.configuration;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

@Bean(destroyMethod = "shutdown")
public RedissonClient redissonClient(
@Value("${spring.data.redis.host:localhost}") String host,
@Value("${spring.data.redis.port:6379}") int port) {
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port);
return Redisson.create(config);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.hubEleven.stock.infrastructure.lock;

import static com.hubEleven.stock.domain.exception.StockErrorCode.STOCK_LOCK_TIMEOUT;

import com.commonLib.common.exception.GlobalException;
import com.hubEleven.stock.application.port.StockLockManager;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class RedissonStockLockManager implements StockLockManager {

private static final int MAX_RETRY_COUNT = 3;
private static final long WAIT_TIME_SECONDS = 3L;
private static final long LEASE_TIME_SECONDS = 5L;
private static final long RETRY_BACKOFF_MILLIS = 100L;

private final RedissonClient redissonClient;

@Override
public <T> T executeWithLock(String lockKey, Supplier<T> supplier) {
RLock lock = redissonClient.getLock(lockKey);
boolean locked = false;

try {
for (int retryCount = 0; retryCount < MAX_RETRY_COUNT; retryCount++) {
locked = lock.tryLock(WAIT_TIME_SECONDS, LEASE_TIME_SECONDS, TimeUnit.SECONDS);
if (locked) {
return supplier.get();
}

Thread.sleep(RETRY_BACKOFF_MILLIS);
}

throw new GlobalException(STOCK_LOCK_TIMEOUT);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new GlobalException(STOCK_LOCK_TIMEOUT);
} finally {
if (locked && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
Comment thread
Copilot marked this conversation as resolved.
}
30 changes: 27 additions & 3 deletions product/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
spring:
application:
name: product-service
config:
import: "configserver:"
data:
redis:
host: ${SPRING_DATA_REDIS_HOST:localhost}
port: ${SPRING_DATA_REDIS_PORT:6379}
cloud:
config:
discovery:
Expand All @@ -16,4 +18,26 @@ eureka:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}}
instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}}

---
# Product Profile
spring:
config:
activate:
on-profile: prod
import: "configserver:"

---
# Test Profile
spring:
config:
activate:
on-profile: test
cloud:
config:
enabled: false

eureka:
client:
enabled: false
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("test")
class ProductApplicationTests {

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.hubEleven.product.stock.application.fixtures;

import com.hubEleven.product.domain.model.Product;
import java.util.UUID;

public class ProductFixture {

// ===== ID =====

public static final UUID COMPANY_ID = UUID.randomUUID();

public static final UUID HUB_ID = UUID.randomUUID();

// ===== Factory Methods =====

public static Product createDefault() {
return Product.create("Default Product", COMPANY_ID, HUB_ID);
}

private ProductFixture() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.hubEleven.product.stock.application.fixtures;

import com.hubEleven.product.domain.model.Product;
import com.hubEleven.stock.domain.model.Stock;
import com.hubEleven.stock.presentation.dto.request.StockRequests;

public class StockFixture {

// ===== Factory Methods =====

public static Stock createFromProductWithQuantity(Product product, int quantity) {
return Stock.create(
product.getProductId(), product.getCompanyId(), product.getHubId(), quantity);
}

public static StockRequests.Decrease decreaseRequest(Product product, int quantity) {
return new StockRequests.Decrease(product.getProductId(), quantity);
}

private StockFixture() {}
}
Loading
Loading