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) { ... }
+ *
+ *
+ *
+ * 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, ...); // 본인 락만 안전 해제
+ * }
+ * }
+ *
+ *
+ * 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 후만 호출. + * + *
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 송금 도메인 — 측정 전 상태 리셋 유틸. + * + *
+ * [TX] begin + * [LOCK] begin — wallet:1 + * (실제 송금) + * [AUDIT] ← publishEvent 직후 즉시 (commit 전, 동기, 같은 스레드) + * [NOTIFY] ← 같은 시점 + * [LOCK] release + * [TX] 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 한계 그대로). + * + *
+ * transferWithFailure(1, 2, 50): + * INSERT / UPDATE — DB 변경 + * publishEvent — listener 즉시 호출 (동기, commit 전) + * [AUDIT] — 감사 기록 (= 5 주차 @Audited 와 같음) + * [NOTIFY] — 알림 발송 (= 외부 시스템 회수 불가) + * throw RuntimeException + * (rollback) — DB 만 취소. listener 는 이미 실행됨. + *+ * + *
./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 (동기 @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