diff --git a/README.md b/README.md index b42c0ac..6f21006 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ | 이름 | 폴더 | 1주차 | 2주차 | 3주차 | 4주차 | 5주차 | 현재 | |---|---|---|---|---|---|---|---| -| 오찬혁 | `chanhyeok` | 선착순 쿠폰 | 호텔 객실 예약 | P2P 송금 (11) | — | 분산락 AOP (8) | 5주차 | +| 오찬혁 | `chanhyeok` | 선착순 쿠폰 | 호텔 객실 예약 | P2P 송금 (11) | 결제 PG 연동 (3) | 분산락 AOP (8) | 5주차 | | 김가빈 | `gabin` | 이중 환불 | 장바구니 결제 | — | 할인 정책 (11) | 캐싱 (5) | 5주차 | | 김민서 | `minseo` | 출퇴근 기록 | 회의실 / 스터디룸 예약 | 티켓 예매 (6) | 인증 전략 (4) | 감사 로그 (1) | 5주차 | | 박수진 | `sujin` | volatile 집중 | 콘서트 좌석 예약 | 주식 매수/매도 (2) | 알림 발송 (1) | 권한 검증 (4) | 5주차 | diff --git a/topics/05-proxy-aop/members/chanhyeok/src/main/java/domain/TransferService.java b/topics/05-proxy-aop/members/chanhyeok/src/main/java/domain/TransferService.java index 621855c..e39f5f7 100644 --- a/topics/05-proxy-aop/members/chanhyeok/src/main/java/domain/TransferService.java +++ b/topics/05-proxy-aop/members/chanhyeok/src/main/java/domain/TransferService.java @@ -25,7 +25,7 @@ public TransferService(DataSource dataSource) { this.dataSource = dataSource; } - @DistributedLock(key = "wallet:#{fromId}", ttlSeconds = 5) + @DistributedLock(key = "wallet:#{#fromId}", ttlSeconds = 5) @Audited(action = "TRANSFER") // Stage4 advice 안-밖 — @Order(1) Lock > @Order(2) Audit public void transfer(long fromId, long toId, BigDecimal amount) { try (Connection conn = dataSource.getConnection()) { diff --git a/topics/06-event/members/chanhyeok/.gitkeep b/topics/06-event/members/chanhyeok/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/topics/06-event/members/chanhyeok/build.gradle b/topics/06-event/members/chanhyeok/build.gradle new file mode 100644 index 0000000..bd4d8f4 --- /dev/null +++ b/topics/06-event/members/chanhyeok/build.gradle @@ -0,0 +1,37 @@ +// 6주차 학습 — Spring Event (publishEvent + @TransactionalEventListener + @Async) +// 5주차 P2P 송금 도메인 (PostgreSQL + Redis + 분산락 AOP) 연장. +// 5주차 @Audited 제거 → publishEvent + AFTER_COMMIT listener 로 옮김. + +plugins { + id 'java' + id 'application' +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter:3.2.0' + implementation 'org.springframework.boot:spring-boot-starter-aop:3.2.0' // 5주차 분산락 AOP + implementation 'org.springframework.boot:spring-boot-starter-jdbc:3.2.0' // @Transactional + JdbcTemplate + + // 5주차 인프라 그대로 + implementation 'org.postgresql:postgresql:42.7.4' + implementation 'io.lettuce:lettuce-core:6.3.0.RELEASE' +} + +application { + mainClass = providers.gradleProperty('mainClass').orElse('stage.Stage1Hello') +} + +// -parameters: AspectJ 어노테이션 파라미터 바인딩 + SpEL 안전장치 +tasks.withType(JavaCompile).configureEach { + options.compilerArgs << '-parameters' +} diff --git a/topics/06-event/members/chanhyeok/gradle/wrapper/gradle-wrapper.jar b/topics/06-event/members/chanhyeok/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/topics/06-event/members/chanhyeok/gradle/wrapper/gradle-wrapper.jar differ diff --git a/topics/06-event/members/chanhyeok/gradle/wrapper/gradle-wrapper.properties b/topics/06-event/members/chanhyeok/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/topics/06-event/members/chanhyeok/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/topics/06-event/members/chanhyeok/gradlew b/topics/06-event/members/chanhyeok/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/topics/06-event/members/chanhyeok/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/topics/06-event/members/chanhyeok/gradlew.bat b/topics/06-event/members/chanhyeok/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/topics/06-event/members/chanhyeok/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/DistributedLock.java b/topics/06-event/members/chanhyeok/src/main/java/domain/DistributedLock.java new file mode 100644 index 0000000..19de1f0 --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/DistributedLock.java @@ -0,0 +1,30 @@ +package domain; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 분산락 자작 어노테이션 — 3 주차 SETNX/Lua/finally 보일러플레이트를 한 줄로. + * + *

사용 예

+ *
+ * @DistributedLock(key = "wallet:#{fromId}", ttlSeconds = 5)
+ * public void transfer(long fromId, long toId, BigDecimal amount) { ... }
+ * 
+ * + *

SpEL

+ * {@code key} 는 SpEL 표현식. 메서드 인자명을 그대로 참조 가능 (#fromId / #toId 등). + * {@code -parameters} 컴파일 옵션 필요 (build.gradle 에 설정됨). + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface DistributedLock { + + /** 락 키 (SpEL 지원). 예: "wallet:#{fromId}" */ + String key(); + + /** TTL — 락 보유자가 죽어도 자동 해제. 기본 5 초 */ + int ttlSeconds() default 5; +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/DistributedLockAspect.java b/topics/06-event/members/chanhyeok/src/main/java/domain/DistributedLockAspect.java new file mode 100644 index 0000000..7bb7fc3 --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/DistributedLockAspect.java @@ -0,0 +1,112 @@ +package domain; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.SetArgs; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.lang.reflect.Method; +import java.util.UUID; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.context.expression.MethodBasedEvaluationContext; +import org.springframework.core.DefaultParameterNameDiscoverer; +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.core.annotation.Order; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.ParserContext; +import org.springframework.expression.common.TemplateParserContext; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.stereotype.Component; + +/** + * 분산락 Aspect — 3 주차 보일러플레이트 흡수. + * + *

흡수하는 코드 패턴 (3 주차 Stage2Distributed)

+ *
+ * String lockKey = "lock:wallet:" + Math.min(fromId, toId);
+ * String lockValue = UUID.randomUUID().toString();
+ * try (StatefulRedisConnection<String, String> rconn = RedisClientFactory.connect()) {
+ *     RedisCommands<String, String> redis = rconn.sync();
+ *     String result = redis.set(lockKey, lockValue, SetArgs.Builder.nx().ex(5));
+ *     if (!"OK".equals(result)) {
+ *         throw new LockAcquireFailedException(...);
+ *     }
+ *     try {
+ *         // 실제 비즈니스 로직
+ *     } finally {
+ *         redis.eval(UNLOCK_LUA, ScriptOutputType.INTEGER, ...);   // 본인 락만 안전 해제
+ *     }
+ * }
+ * 
+ * + *

실패 정책

+ * fail-fast — 락 획득 실패 시 즉시 {@link LockAcquireFailedException} 던짐. + * 호출자가 재시도 결정 (3 주차 트레이드오프 그대로). + */ +@Aspect +@Component +@Order(1) // Stage4 advice 안-밖에서 가장 바깥 — 락 잡은 후 AuditAspect(@Order 2) 동작 +public class DistributedLockAspect { + + private static final String UNLOCK_LUA = """ + if redis.call('get', KEYS[1]) == ARGV[1] then + return redis.call('del', KEYS[1]) + else + return 0 + end + """; + + private final RedisClient redisClient; + private final ExpressionParser parser = new SpelExpressionParser(); + private final ParserContext templateContext = new TemplateParserContext(); // "#{...}" 템플릿 + private final ParameterNameDiscoverer paramDiscoverer = new DefaultParameterNameDiscoverer(); + + public DistributedLockAspect(RedisClient redisClient) { + this.redisClient = redisClient; + } + + @Around("@annotation(distributedLock)") + public Object lock(ProceedingJoinPoint pjp, DistributedLock distributedLock) throws Throwable { + String key = "lock:" + resolveKey(pjp, distributedLock.key()); + String value = UUID.randomUUID().toString(); + + try (StatefulRedisConnection conn = redisClient.connect()) { + RedisCommands redis = conn.sync(); + + // 1. SETNX + TTL — 원자적 잠금 + String result = redis.set(key, value, + SetArgs.Builder.nx().ex(distributedLock.ttlSeconds())); + if (!"OK".equals(result)) { + throw new LockAcquireFailedException(key); + } + + try { + // 2. 실제 비즈니스 로직 (사용자 메서드) + return pjp.proceed(); + } finally { + // 3. Lua script — 본인 락만 안전 해제 + redis.eval(UNLOCK_LUA, ScriptOutputType.INTEGER, + new String[]{key}, value); + } + } + } + + /** SpEL 로 메서드 인자 참조해서 키 동적 생성 (예: "wallet:#{fromId}") */ + private String resolveKey(ProceedingJoinPoint pjp, String expression) { + MethodSignature signature = (MethodSignature) pjp.getSignature(); + Method method = signature.getMethod(); + MethodBasedEvaluationContext context = new MethodBasedEvaluationContext( + null, method, pjp.getArgs(), paramDiscoverer); + // "wallet:#{fromId}" → "wallet:1" (SpEL template 모드) + return parser.parseExpression(expression, templateContext).getValue(context, String.class); + } + + public static class LockAcquireFailedException extends RuntimeException { + public LockAcquireFailedException(String key) { + super("락 획득 실패 — key=" + key); + } + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/P2PWallet.java b/topics/06-event/members/chanhyeok/src/main/java/domain/P2PWallet.java new file mode 100644 index 0000000..a19fd6f --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/P2PWallet.java @@ -0,0 +1,299 @@ +package domain; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * P2P 송금 도메인 — 3 주차 락 학습용. + * + *

row 3 개 동시 변경

+ * 송금 1 건 처리 시 다음 row 가 한 트랜잭션 안에서 모두 변경되어야 정합성 유지: + * + * + *

락 순서 (데드락 회피)

+ * {@code min(fromId, toId) → max(fromId, toId) → fee_revenue(id=1)}. + * 모든 트랜잭션이 동일한 순서로 락을 잡으면 순환 대기 X → 데드락 X. + * + *

read-modify-write 패턴 강제

+ * {@code SELECT balance, daily_sent_amount} → 앱에서 검증 → {@code UPDATE} 로 짠다. + * {@code UPDATE balance = balance - ?} 같은 atomic UPDATE 로 짜면 + * PG row-lock 이 자동으로 막아서 락 학습 포인트가 안 보임 (1, 2 주차 동일 원칙). + * + *

일일 한도 검증

+ * 잔액 검증 + 일일 한도 검증 2 단계 (RMW 단계 추가). 한도 초과 시 false 반환. + */ +public class P2PWallet { + + /** 1 일 송금 한도 — RMW 검증 대상 */ + public static final BigDecimal DAILY_LIMIT = new BigDecimal("500000"); + /** 송금 수수료 — 측정 단순화를 위해 고정 */ + public static final BigDecimal FEE = new BigDecimal("10"); + + private static final String SELECT_WALLET_FOR_UPDATE_SQL = + "SELECT balance, daily_sent_amount FROM user_wallet WHERE id = ? FOR UPDATE"; + + private static final String SELECT_WALLET_VERSION_SQL = + "SELECT balance, daily_sent_amount, version FROM user_wallet WHERE id = ?"; + + private static final String SELECT_FEE_FOR_UPDATE_SQL = + "SELECT total_collected FROM fee_revenue WHERE id = 1 FOR UPDATE"; + + private static final String SELECT_FEE_VERSION_SQL = + "SELECT total_collected, version FROM fee_revenue WHERE id = 1"; + + private static final String UPDATE_WALLET_SQL = + "UPDATE user_wallet SET balance = ?, daily_sent_amount = ? WHERE id = ?"; + + private static final String UPDATE_WALLET_OPTIMISTIC_SQL = + "UPDATE user_wallet SET balance = ?, daily_sent_amount = ?, version = version + 1 " + + "WHERE id = ? AND version = ?"; + + private static final String UPDATE_FEE_SQL = + "UPDATE fee_revenue SET total_collected = ? WHERE id = 1"; + + private static final String UPDATE_FEE_OPTIMISTIC_SQL = + "UPDATE fee_revenue SET total_collected = ?, version = version + 1 " + + "WHERE id = 1 AND version = ?"; + + private static final String INSERT_LOG_SQL = + "INSERT INTO transfer_log (from_id, to_id, amount, fee) VALUES (?, ?, ?, ?)"; + + /** + * 비관적 락 — row 3 개를 정해진 순서로 잠근다. + * + * @return 성공 시 true. 잔액 부족 / 일일 한도 초과 시 false. + */ + public boolean transferPessimistic(Connection conn, long fromId, long toId, BigDecimal amount) + throws SQLException { + + long lockFirst = Math.min(fromId, toId); + long lockSecond = Math.max(fromId, toId); + + Wallet first = selectForUpdate(conn, lockFirst); + Wallet second = selectForUpdate(conn, lockSecond); + BigDecimal feeTotal = selectFeeForUpdate(conn); + + Wallet from = (fromId == lockFirst) ? first : second; + Wallet to = (toId == lockFirst) ? first : second; + + if (from.balance.compareTo(amount.add(FEE)) < 0) return false; + if (from.dailySent.add(amount).compareTo(DAILY_LIMIT) > 0) return false; + + updateWallet(conn, fromId, from.balance.subtract(amount).subtract(FEE), from.dailySent.add(amount)); + updateWallet(conn, toId, to.balance.add(amount), to.dailySent); + updateFee(conn, feeTotal.add(FEE)); + insertLog(conn, fromId, toId, amount, FEE); + return true; + } + + /** + * 낙관적 락 — 3 개 row 의 version 비교 후 UPDATE. 충돌 시 재시도. + * + *

partial update (일부 row UPDATE 성공 / 일부 실패) 시 반드시 rollback — + * 안 그러면 다음 attempt 가 부분 반영된 상태를 다시 읽어서 정합성 깨짐. + * + * @return 성공 시 true. 잔액 부족 / 한도 초과 / 재시도 한계 초과 시 false (starvation). + */ + public boolean transferOptimistic(Connection conn, long fromId, long toId, + BigDecimal amount, int maxRetries) throws SQLException { + + for (int attempt = 0; attempt < maxRetries; attempt++) { + WalletV from = selectWithVersion(conn, fromId); + WalletV to = selectWithVersion(conn, toId); + FeeV feeV = selectFeeWithVersion(conn); + + if (from.balance.compareTo(amount.add(FEE)) < 0) return false; + if (from.dailySent.add(amount).compareTo(DAILY_LIMIT) > 0) return false; + + int affFrom = updateWalletOptimistic(conn, fromId, + from.balance.subtract(amount).subtract(FEE), + from.dailySent.add(amount), + from.version); + if (affFrom != 1) { + // fromId 변경 X — rollback 불필요. 재시도. + continue; + } + + int affTo = updateWalletOptimistic(conn, toId, + to.balance.add(amount), to.dailySent, to.version); + if (affTo != 1) { + // ⚠️ partial — fromId 이미 차감. rollback 안 하면 정합성 깨짐. + conn.rollback(); + continue; + } + + int affFee = updateFeeOptimistic(conn, feeV.total.add(FEE), feeV.version); + if (affFee != 1) { + // ⚠️ partial — 두 wallet 이미 변경. rollback 필수. + conn.rollback(); + continue; + } + + insertLog(conn, fromId, toId, amount, FEE); + return true; + } + return false; + } + + /** + * 락 없이 RMW (분산락 stage 에서 외부 락 잡고 호출). + */ + public boolean transferRaw(Connection conn, long fromId, long toId, BigDecimal amount) + throws SQLException { + + Wallet from = selectWallet(conn, fromId); + Wallet to = selectWallet(conn, toId); + BigDecimal feeTotal = selectFee(conn); + + if (from.balance.compareTo(amount.add(FEE)) < 0) return false; + if (from.dailySent.add(amount).compareTo(DAILY_LIMIT) > 0) return false; + + updateWallet(conn, fromId, from.balance.subtract(amount).subtract(FEE), from.dailySent.add(amount)); + updateWallet(conn, toId, to.balance.add(amount), to.dailySent); + updateFee(conn, feeTotal.add(FEE)); + insertLog(conn, fromId, toId, amount, FEE); + return true; + } + + // ---- read helpers ---- + + private Wallet selectForUpdate(Connection conn, long id) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(SELECT_WALLET_FOR_UPDATE_SQL)) { + ps.setLong(1, id); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return new Wallet(rs.getBigDecimal(1), rs.getBigDecimal(2)); + } + } + } + + private Wallet selectWallet(Connection conn, long id) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement( + "SELECT balance, daily_sent_amount FROM user_wallet WHERE id = ?")) { + ps.setLong(1, id); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return new Wallet(rs.getBigDecimal(1), rs.getBigDecimal(2)); + } + } + } + + private WalletV selectWithVersion(Connection conn, long id) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(SELECT_WALLET_VERSION_SQL)) { + ps.setLong(1, id); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return new WalletV(rs.getBigDecimal(1), rs.getBigDecimal(2), rs.getLong(3)); + } + } + } + + private BigDecimal selectFeeForUpdate(Connection conn) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(SELECT_FEE_FOR_UPDATE_SQL); + ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getBigDecimal(1); + } + } + + private BigDecimal selectFee(Connection conn) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement( + "SELECT total_collected FROM fee_revenue WHERE id = 1"); + ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getBigDecimal(1); + } + } + + private FeeV selectFeeWithVersion(Connection conn) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(SELECT_FEE_VERSION_SQL); + ResultSet rs = ps.executeQuery()) { + rs.next(); + return new FeeV(rs.getBigDecimal(1), rs.getLong(2)); + } + } + + // ---- write helpers ---- + + private void updateWallet(Connection conn, long id, BigDecimal balance, BigDecimal dailySent) + throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(UPDATE_WALLET_SQL)) { + ps.setBigDecimal(1, balance); + ps.setBigDecimal(2, dailySent); + ps.setLong(3, id); + ps.executeUpdate(); + } + } + + private int updateWalletOptimistic(Connection conn, long id, BigDecimal balance, + BigDecimal dailySent, long expectedVersion) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(UPDATE_WALLET_OPTIMISTIC_SQL)) { + ps.setBigDecimal(1, balance); + ps.setBigDecimal(2, dailySent); + ps.setLong(3, id); + ps.setLong(4, expectedVersion); + return ps.executeUpdate(); + } + } + + private void updateFee(Connection conn, BigDecimal newTotal) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(UPDATE_FEE_SQL)) { + ps.setBigDecimal(1, newTotal); + ps.executeUpdate(); + } + } + + private int updateFeeOptimistic(Connection conn, BigDecimal newTotal, long expectedVersion) + throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(UPDATE_FEE_OPTIMISTIC_SQL)) { + ps.setBigDecimal(1, newTotal); + ps.setLong(2, expectedVersion); + return ps.executeUpdate(); + } + } + + private void insertLog(Connection conn, long fromId, long toId, BigDecimal amount, BigDecimal fee) + throws SQLException { + try (PreparedStatement ps = conn.prepareStatement(INSERT_LOG_SQL)) { + ps.setLong(1, fromId); + ps.setLong(2, toId); + ps.setBigDecimal(3, amount); + ps.setBigDecimal(4, fee); + ps.executeUpdate(); + } + } + + // ---- 측정 후 검증용 ---- + + public BigDecimal balanceOf(Connection conn, long id) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement( + "SELECT balance FROM user_wallet WHERE id = ?")) { + ps.setLong(1, id); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getBigDecimal(1); + } + } + } + + public BigDecimal feeTotal(Connection conn) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement( + "SELECT total_collected FROM fee_revenue WHERE id = 1"); + ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getBigDecimal(1); + } + } + + private record Wallet(BigDecimal balance, BigDecimal dailySent) {} + private record WalletV(BigDecimal balance, BigDecimal dailySent, long version) {} + private record FeeV(BigDecimal total, long version) {} +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/TransferAfterCommitListeners.java b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferAfterCommitListeners.java new file mode 100644 index 0000000..65a39b8 --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferAfterCommitListeners.java @@ -0,0 +1,37 @@ +package domain; + +import org.springframework.transaction.event.TransactionPhase; +import org.springframework.transaction.event.TransactionalEventListener; + +/** + * STAGE 3 — @TransactionalEventListener(AFTER_COMMIT) — commit 후만 호출. + * + *

STAGE 2 (동기) 와의 차이

+ * + * + *

5 주차 → 6 주차 한계 해결의 본질

+ * 트랜잭션 결과 기반 자동 분기 — 외부 호출이 트랜잭션 commit 보장 후에만 실행. + * + *

등록

+ * @Component 없음 — STAGE 3 의 @SpringBootApplication 에서 명시적 @Bean 으로 등록. + */ +public class TransferAfterCommitListeners { + + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void onAudit(TransferCompletedEvent e) { + System.out.println(" [AUDIT-AC] " + e.fromId() + " → " + e.toId() + + " amount=" + e.amount() + + " at=" + e.completedAt() + + " thread=" + Thread.currentThread().getName()); + } + + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void onNotify(TransferCompletedEvent e) { + System.out.println(" [NOTIFY-AC] 수신자 " + e.toId() + " 알림 발송" + + " thread=" + Thread.currentThread().getName()); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/TransferCompletedEvent.java b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferCompletedEvent.java new file mode 100644 index 0000000..d91ef94 --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferCompletedEvent.java @@ -0,0 +1,28 @@ +package domain; + +import java.math.BigDecimal; +import java.time.Instant; + +/** + * 송금 완료 이벤트 — 6 주차 publishEvent payload. + * + *

설계 원칙

+ * + * + *

5 주차 → 6 주차 매핑

+ * + */ +public record TransferCompletedEvent( + long fromId, + long toId, + BigDecimal amount, + Instant completedAt +) {} diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/TransferEventListeners.java b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferEventListeners.java new file mode 100644 index 0000000..14e5a2a --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferEventListeners.java @@ -0,0 +1,34 @@ +package domain; + +import org.springframework.context.event.EventListener; + +/** + * STAGE 1/2 — 동기 @EventListener (= 5 주차 한계 그대로). + * + *

특징

+ * + * + *

등록

+ * @Component 없음 — STAGE 1/2 의 @SpringBootApplication 에서 명시적 @Bean 으로 등록. + * STAGE 3 (TransferAfterCommitListeners) 와의 독립 보장. + */ +public class TransferEventListeners { + + @EventListener + public void onAudit(TransferCompletedEvent e) { + System.out.println(" [AUDIT] " + e.fromId() + " → " + e.toId() + + " amount=" + e.amount() + + " at=" + e.completedAt() + + " thread=" + Thread.currentThread().getName()); + } + + @EventListener + public void onNotify(TransferCompletedEvent e) { + System.out.println(" [NOTIFY] 수신자 " + e.toId() + " 알림 발송" + + " thread=" + Thread.currentThread().getName()); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/domain/TransferService.java b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferService.java new file mode 100644 index 0000000..b9cbf6c --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/domain/TransferService.java @@ -0,0 +1,101 @@ +package domain; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import javax.sql.DataSource; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * 6 주차 변환 — 5 주차 TransferService 에서 @Audited 제거 + @Transactional 적용 + publishEvent 추가. + * + *

5 주차 → 6 주차 변경점

+ * + * + *

유지된 부분

+ * + */ +@Service +public class TransferService { + + private final DataSource dataSource; + private final ApplicationEventPublisher publisher; + private final P2PWallet wallet = new P2PWallet(); + + public TransferService(DataSource dataSource, ApplicationEventPublisher publisher) { + this.dataSource = dataSource; + this.publisher = publisher; + } + + @DistributedLock(key = "wallet:#{#fromId}", ttlSeconds = 5) + @Transactional + public void transfer(long fromId, long toId, BigDecimal amount) { + Connection conn = DataSourceUtils.getConnection(dataSource); + try { + wallet.transferRaw(conn, fromId, toId, amount); + } catch (SQLException e) { + throw new RuntimeException(e); + } finally { + DataSourceUtils.releaseConnection(conn, dataSource); + } + + // commit 후 처리는 TransferEventListeners 의 AFTER_COMMIT 으로 + publisher.publishEvent(new TransferCompletedEvent(fromId, toId, amount, Instant.now())); + } + + /** + * STAGE 2 한계 재현용 — 송금 + publishEvent 후 일부러 예외 → rollback. + * + *

관찰

+ * + */ + @DistributedLock(key = "wallet:#{#fromId}", ttlSeconds = 5) + @Transactional + public void transferWithFailure(long fromId, long toId, BigDecimal amount) { + Connection conn = DataSourceUtils.getConnection(dataSource); + try { + wallet.transferRaw(conn, fromId, toId, amount); + } catch (SQLException e) { + throw new RuntimeException(e); + } finally { + DataSourceUtils.releaseConnection(conn, dataSource); + } + + publisher.publishEvent(new TransferCompletedEvent(fromId, toId, amount, Instant.now())); + + // ★ 일부러 예외 — rollback 시뮬레이션. publishEvent 후라 listener 는 이미 실행됨 + throw new RuntimeException("의도적 실패 (rollback 학습용)"); + } + + public BigDecimal balanceOf(long id) { + try (Connection conn = dataSource.getConnection()) { + return wallet.balanceOf(conn, id); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public BigDecimal feeTotal() { + try (Connection conn = dataSource.getConnection()) { + return wallet.feeTotal(conn); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/infra/MeasurementLog.java b/topics/06-event/members/chanhyeok/src/main/java/infra/MeasurementLog.java new file mode 100644 index 0000000..dcb65cb --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/infra/MeasurementLog.java @@ -0,0 +1,94 @@ +package infra; + +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * 측정 결과를 본인 폴더의 measurements.md 파일에 자동 누적 기록. + * (1, 2 주차 example 과 동일 패턴) + * + *

자동 위치 감지

+ * IntelliJ Working Directory 설정과 무관하게, 이 클래스의 실제 위치에서 + * 위로 올라가며 build.gradle 가진 폴더를 찾아 그 안에 measurements.md 를 만든다. + * + *

3 주차 측정 필드

+ * + * + * 3 주차에선 두 번째 시그니처 주로 사용. {@code failed} 자리에 비관 락의 데드락 횟수 / + * 낙관 락의 재시도 횟수 / 분산 락의 lock 획득 실패 모두 기록. + */ +public final class MeasurementLog { + + private static final Path FILE = resolveFile(); + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("MM-dd HH:mm"); + + private MeasurementLog() {} + + public static void save(String stage, String method, double misses, double millis) { + try { + if (!Files.exists(FILE)) { + Files.writeString(FILE, + "# 측정 기록\n\n자동 누적. 옆에 해석 메모는 직접 추가하세요.\n\n"); + } + + String line = String.format("- [%s] %s · %s: 누락 %.1f / %.1fms%n", + LocalDateTime.now().format(TIME), stage, method, misses, millis); + Files.writeString(FILE, line, StandardOpenOption.APPEND); + + System.out.println("→ " + FILE.toAbsolutePath() + " 에 기록됨"); + } catch (IOException e) { + System.err.println("⚠️ measurements.md 기록 실패: " + e.getMessage()); + } + } + + public static void save(String stage, String method, double misses, double failed, double millis) { + try { + if (!Files.exists(FILE)) { + Files.writeString(FILE, + "# 측정 기록\n\n자동 누적. 옆에 해석 메모는 직접 추가하세요.\n\n"); + } + + String line = String.format("- [%s] %s · %s: 누락 %.1f / 실패 %.1f / %.1fms%n", + LocalDateTime.now().format(TIME), stage, method, misses, failed, millis); + Files.writeString(FILE, line, StandardOpenOption.APPEND); + + System.out.println("→ " + FILE.toAbsolutePath() + " 에 기록됨"); + } catch (IOException e) { + System.err.println("⚠️ measurements.md 기록 실패: " + e.getMessage()); + } + } + + private static Path resolveFile() { + try { + var domain = MeasurementLog.class.getProtectionDomain(); + if (domain == null) return Path.of("measurements.md"); + var codeSource = domain.getCodeSource(); + if (codeSource == null) return Path.of("measurements.md"); + URL location = codeSource.getLocation(); + if (location == null) return Path.of("measurements.md"); + + Path start = Path.of(location.toURI()); + if (Files.isRegularFile(start)) { + start = start.getParent(); + } + + Path current = start; + for (int i = 0; i < 10 && current != null; i++) { + if (Files.exists(current.resolve("build.gradle")) + || Files.exists(current.resolve("build.gradle.kts"))) { + return current.resolve("measurements.md"); + } + current = current.getParent(); + } + } catch (Exception ignored) {} + return Path.of("measurements.md"); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/infra/RedisConfig.java b/topics/06-event/members/chanhyeok/src/main/java/infra/RedisConfig.java new file mode 100644 index 0000000..4de2faf --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/infra/RedisConfig.java @@ -0,0 +1,19 @@ +package infra; + +import io.lettuce.core.RedisClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Redis 클라이언트 Spring Bean 등록. + * + *

3 주차 {@code RedisClientFactory} 의 정적 싱글턴 → 4 주차 학습대로 {@code @Bean(destroyMethod="shutdown")} 한 줄. + */ +@Configuration +public class RedisConfig { + + @Bean(destroyMethod = "shutdown") + public RedisClient redisClient() { + return RedisClient.create("redis://localhost:6379"); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/infra/SchemaBootstrap.java b/topics/06-event/members/chanhyeok/src/main/java/infra/SchemaBootstrap.java new file mode 100644 index 0000000..c7e56bd --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/infra/SchemaBootstrap.java @@ -0,0 +1,82 @@ +package infra; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +/** + * P2P 송금 도메인 — 측정 전 상태 리셋 유틸. + * + *

왜 매번 리셋하나

+ * 1, 2 주차 측정 원칙과 동일 — 이전 측정 잔여 상태가 다음 측정에 영향을 주면 + * 결과 해석이 어려워진다. 명시적 초기화 + 시드. + * + *

리셋 대상

+ * + * + *

row 구성 이유

+ * user_wallet 2 개 → 데드락 학습 (양방향 송금에서 락 순서 깸). + * fee_revenue 1 개 → 핫스팟 학습 (모든 송금이 한 row 에 몰림). + */ +public final class SchemaBootstrap { + + private SchemaBootstrap() {} + + public static void reset(DataSource ds) throws SQLException { + try (Connection c = ds.getConnection(); Statement s = c.createStatement()) { + + s.execute(""" + CREATE TABLE IF NOT EXISTS user_wallet ( + id BIGINT PRIMARY KEY, + balance NUMERIC NOT NULL, + daily_sent_amount NUMERIC NOT NULL DEFAULT 0, + version BIGINT NOT NULL DEFAULT 0 + ) + """); + + s.execute(""" + CREATE TABLE IF NOT EXISTS fee_revenue ( + id BIGINT PRIMARY KEY, + total_collected NUMERIC NOT NULL, + version BIGINT NOT NULL DEFAULT 0 + ) + """); + + s.execute(""" + CREATE TABLE IF NOT EXISTS transfer_log ( + id BIGSERIAL PRIMARY KEY, + from_id BIGINT NOT NULL, + to_id BIGINT NOT NULL, + amount NUMERIC NOT NULL, + fee NUMERIC NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """); + + // 시드 + 리셋 + s.execute(""" + INSERT INTO user_wallet (id, balance, daily_sent_amount, version) + VALUES (1, 1000000, 0, 0), (2, 1000000, 0, 0) + ON CONFLICT (id) DO UPDATE + SET balance = EXCLUDED.balance, + daily_sent_amount = 0, + version = 0 + """); + + s.execute(""" + INSERT INTO fee_revenue (id, total_collected, version) + VALUES (1, 0, 0) + ON CONFLICT (id) DO UPDATE + SET total_collected = 0, + version = 0 + """); + + s.execute("TRUNCATE TABLE transfer_log RESTART IDENTITY"); + } + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/stage/Stage1Hello.java b/topics/06-event/members/chanhyeok/src/main/java/stage/Stage1Hello.java new file mode 100644 index 0000000..7fec4db --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/stage/Stage1Hello.java @@ -0,0 +1,78 @@ +package stage; + +import domain.TransferEventListeners; +import domain.TransferService; +import infra.SchemaBootstrap; +import java.math.BigDecimal; +import javax.sql.DataSource; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; + +/** + * STAGE 1 — 본인 도메인 첫 진입. + * + *

5 주차 → 6 주차 가장 작은 변경

+ * + * + *

예상 출력 순서

+ *
+ * [TX] begin
+ *   [LOCK] begin — wallet:1
+ *     (실제 송금)
+ *     [AUDIT]  ← publishEvent 직후 즉시 (commit 전, 동기, 같은 스레드)
+ *     [NOTIFY] ← 같은 시점
+ *   [LOCK] release
+ * [TX] commit
+ * 
+ * + *

이 시점의 한계 — 5 주차와 동일

+ * listener 가 commit 전 호출 → rollback 시 audit / notify 이미 실행됨. + * STAGE 2 에서 @TransactionalEventListener(AFTER_COMMIT) 으로 옮겨 해결. + * + *

실행

+ *
./gradlew run -PmainClass=stage.Stage1Hello
+ */ +@SpringBootApplication(scanBasePackages = {"domain", "infra"}) +public class Stage1Hello { + + @Bean + public TransferEventListeners syncListeners() { + return new TransferEventListeners(); + } + + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext ctx = SpringApplication.run(Stage1Hello.class, args); + + DataSource ds = ctx.getBean(DataSource.class); + SchemaBootstrap.reset(ds); + + TransferService svc = ctx.getBean(TransferService.class); + + System.out.println(); + System.out.println("=== STAGE 1 — TransferService + publishEvent + @EventListener 동기 ==="); + System.out.println(); + + System.out.println("--- transfer(1 → 2, 100) 정상 송금 ---"); + svc.transfer(1L, 2L, new BigDecimal("100")); + + System.out.println(); + System.out.println("--- balance / fee 확인 ---"); + System.out.println(" id=1 잔액 = " + svc.balanceOf(1L)); + System.out.println(" id=2 잔액 = " + svc.balanceOf(2L)); + System.out.println(" fee 누적 = " + svc.feeTotal()); + + System.out.println(); + System.out.println("[학습 포인트]"); + System.out.println(" · publisher (transfer) + listener (audit/notify) 같은 스레드 = 동기"); + System.out.println(" · listener 가 publishEvent 직후 즉시 실행 — commit 전"); + System.out.println(" · 5 주차 @Audited 한계와 동일 — STAGE 2 에서 AFTER_COMMIT 으로 해결"); + + ctx.close(); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/stage/Stage2BeforeCommitTrap.java b/topics/06-event/members/chanhyeok/src/main/java/stage/Stage2BeforeCommitTrap.java new file mode 100644 index 0000000..f8e2da3 --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/stage/Stage2BeforeCommitTrap.java @@ -0,0 +1,92 @@ +package stage; + +import domain.TransferEventListeners; +import domain.TransferService; +import infra.SchemaBootstrap; +import java.math.BigDecimal; +import javax.sql.DataSource; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; + +/** + * STAGE 2 — @EventListener 한계 재현 (= 5 주차 @Audited 한계 그대로). + * + *

시나리오

+ *
    + *
  1. 정상 송금 — INSERT + listener 호출 + commit
  2. + *
  3. 실패 송금 — INSERT + listener 호출 + 예외 → rollback (listener 는 이미 호출됨)
  4. + *
+ * + *

한계 재현 포인트

+ *
+ * transferWithFailure(1, 2, 50):
+ *   INSERT / UPDATE — DB 변경
+ *   publishEvent    — listener 즉시 호출 (동기, commit 전)
+ *     [AUDIT]       — 감사 기록 (= 5 주차 @Audited 와 같음)
+ *     [NOTIFY]      — 알림 발송 (= 외부 시스템 회수 불가)
+ *   throw RuntimeException
+ *   (rollback)      — DB 만 취소. listener 는 이미 실행됨.
+ * 
+ * + *

balance 검증

+ * 두 송금 후 — 정상 송금만 반영됐어야 함: + * + * + *

해결 → STAGE 3 (AFTER_COMMIT)

+ * + *

실행

+ *
./gradlew run -PmainClass=stage.Stage2BeforeCommitTrap
+ */ +@SpringBootApplication(scanBasePackages = {"domain", "infra"}) +public class Stage2BeforeCommitTrap { + + @Bean + public TransferEventListeners syncListeners() { + return new TransferEventListeners(); + } + + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext ctx = SpringApplication.run(Stage2BeforeCommitTrap.class, args); + + DataSource ds = ctx.getBean(DataSource.class); + SchemaBootstrap.reset(ds); + + TransferService svc = ctx.getBean(TransferService.class); + + System.out.println(); + System.out.println("=== STAGE 2 — @EventListener 한계 (commit 전 호출 → rollback 무력) ==="); + + System.out.println(); + System.out.println("--- (1) 정상 송금 transfer(1 → 2, 100) ---"); + svc.transfer(1L, 2L, new BigDecimal("100")); + + System.out.println(); + System.out.println("--- (2) 실패 송금 transferWithFailure(1 → 2, 50) — 일부러 예외 ---"); + try { + svc.transferWithFailure(1L, 2L, new BigDecimal("50")); + } catch (RuntimeException e) { + System.out.println(" [caller] 예외 잡음: " + e.getMessage()); + } + + System.out.println(); + System.out.println("--- balance / fee 확인 ---"); + System.out.println(" id=1 잔액 = " + svc.balanceOf(1L) + " (예상: 999890, 정상 송금만 반영)"); + System.out.println(" id=2 잔액 = " + svc.balanceOf(2L) + " (예상: 1000100)"); + System.out.println(" fee 누적 = " + svc.feeTotal() + " (예상: 10)"); + + System.out.println(); + System.out.println("[학습 포인트] — 5 주차 한계 그대로 재현"); + System.out.println(" · DB INSERT/UPDATE = rollback 으로 취소 ✓"); + System.out.println(" · [AUDIT] / [NOTIFY] = publishEvent 시점에 이미 실행됨 ✗"); + System.out.println(" · 실패 케이스에서도 사용자에게 \"송금 성공\" 알림 발송됨 (회수 불가)"); + System.out.println(" · 해결 → STAGE 3 (@TransactionalEventListener(AFTER_COMMIT))"); + + ctx.close(); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/java/stage/Stage3AfterCommit.java b/topics/06-event/members/chanhyeok/src/main/java/stage/Stage3AfterCommit.java new file mode 100644 index 0000000..3b5f64f --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/java/stage/Stage3AfterCommit.java @@ -0,0 +1,83 @@ +package stage; + +import domain.TransferAfterCommitListeners; +import domain.TransferService; +import infra.SchemaBootstrap; +import java.math.BigDecimal; +import javax.sql.DataSource; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; + +/** + * STAGE 3 — @TransactionalEventListener(AFTER_COMMIT) 해결. + * + *

STAGE 2 와 같은 시나리오, 다른 listener

+ * + * + *

STAGE 2 vs STAGE 3 출력 비교

+ *
+ * STAGE 2 (동기 @EventListener):
+ *   (1) 정상   [AUDIT] [NOTIFY] (commit 전, 동기)
+ *   (2) 실패   [AUDIT] [NOTIFY] (commit 전, rollback 돼도 이미 호출) ✗
+ *
+ * STAGE 3 (@TransactionalEventListener(AFTER_COMMIT)):
+ *   (1) 정상   [AUDIT-AC] [NOTIFY-AC] (commit 후 호출)
+ *   (2) 실패   (listener 호출 X — 외부 호출 안전) ✓
+ * 
+ * + *

실행

+ *
./gradlew run -PmainClass=stage.Stage3AfterCommit
+ */ +@SpringBootApplication(scanBasePackages = {"domain", "infra"}) +public class Stage3AfterCommit { + + @Bean + public TransferAfterCommitListeners afterCommitListeners() { + return new TransferAfterCommitListeners(); + } + + public static void main(String[] args) throws Exception { + ConfigurableApplicationContext ctx = SpringApplication.run(Stage3AfterCommit.class, args); + + DataSource ds = ctx.getBean(DataSource.class); + SchemaBootstrap.reset(ds); + + TransferService svc = ctx.getBean(TransferService.class); + + System.out.println(); + System.out.println("=== STAGE 3 — @TransactionalEventListener(AFTER_COMMIT) 해결 ==="); + + System.out.println(); + System.out.println("--- (1) 정상 송금 transfer(1 → 2, 100) ---"); + svc.transfer(1L, 2L, new BigDecimal("100")); + + System.out.println(); + System.out.println("--- (2) 실패 송금 transferWithFailure(1 → 2, 50) — 일부러 예외 ---"); + try { + svc.transferWithFailure(1L, 2L, new BigDecimal("50")); + } catch (RuntimeException e) { + System.out.println(" [caller] 예외 잡음: " + e.getMessage()); + System.out.println(" ← listener (AC) 호출 안 됨 (commit 안 됐으므로)"); + } + + System.out.println(); + System.out.println("--- balance / fee 확인 ---"); + System.out.println(" id=1 잔액 = " + svc.balanceOf(1L) + " (예상: 999890, 정상 송금만 반영)"); + System.out.println(" id=2 잔액 = " + svc.balanceOf(2L) + " (예상: 1000100)"); + System.out.println(" fee 누적 = " + svc.feeTotal() + " (예상: 10)"); + + System.out.println(); + System.out.println("[학습 포인트] — 5 주차 한계 해결"); + System.out.println(" · 정상 commit → [AUDIT-AC] / [NOTIFY-AC] 호출 ✓"); + System.out.println(" · rollback → listener 호출 X ✓ — 외부 호출 안전"); + System.out.println(" · 변경점은 어노테이션 한 줄 (@EventListener → @TransactionalEventListener(AFTER_COMMIT))"); + System.out.println(" · STAGE 2 의 같은 시나리오와 출력 직접 비교"); + + ctx.close(); + } +} diff --git a/topics/06-event/members/chanhyeok/src/main/resources/application.properties b/topics/06-event/members/chanhyeok/src/main/resources/application.properties new file mode 100644 index 0000000..fe5a749 --- /dev/null +++ b/topics/06-event/members/chanhyeok/src/main/resources/application.properties @@ -0,0 +1,9 @@ +# 3주차 docker-compose 그대로 — PostgreSQL + Redis +spring.datasource.url=jdbc:postgresql://localhost:5433/csstudy +spring.datasource.username=csstudy +spring.datasource.password=csstudy1234 +spring.datasource.driver-class-name=org.postgresql.Driver +spring.datasource.hikari.maximum-pool-size=50 + +# Spring AOP 기본 = CGLIB (Spring Boot 2.0+) +spring.aop.proxy-target-class=true