refactor : 스프링 이벤트 처리 예제 코드 spring-event 브랜치로부터 이관
This commit is contained in:
37
놀이터(예제 코드 작성)/spring-event/.gitignore
vendored
Normal file
37
놀이터(예제 코드 작성)/spring-event/.gitignore
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
39
놀이터(예제 코드 작성)/spring-event/INDEX.md
Normal file
39
놀이터(예제 코드 작성)/spring-event/INDEX.md
Normal file
@@ -0,0 +1,39 @@
|
||||
### 🚀 step1
|
||||
|
||||
- 현재 코드를 분석 하면서 어떤 점을 고치고 싶은지 니즈를 파악해본다.
|
||||
|
||||
### 🚀 step2
|
||||
|
||||
- 상속 기반의 이벤트로 변경 해본다.
|
||||
- 이벤트 객체를 만들기 위해 ApplicationEvent 를 상속 받아 데이터 전달을 위해 객체를 만들어본다.
|
||||
- 이벤트 객체로 부터 전달 받을 EventListener 구현체를 만들어본다.
|
||||
- ApplicationEventPublisher 를 주입 받아서 이벤트를 발행 시킨다.
|
||||
- 테스트 코드 작성
|
||||
> Mockito 활용
|
||||
|
||||
### 📖 살펴볼 객체
|
||||
|
||||
- `AbstractApplicationContext` 를 intellij 의 diagram 을 통해서 구조를 살펴보면 `ApplicationEventPublisher` 를 상속 받고 있습니다.
|
||||
- `AbstractApplicationContext`::publishEvent 메소드를 보면 이벤트의 발행이 어떻게 되는지 알 수 있습니다.
|
||||
|
||||
> 조금 설명을 드리면 위의 메소드 안에서 ApplicationEventMulticaster 를 주입 받아 이벤트를 실행 시키는데 구현체 중 `SimpleApplicationEventMulticater` 를 살펴보면 (위와 같이 다이어그램으로 표현) multicastEvent 메소드를 통해서 빈으로 등록된 이벤트 객체를 실행을 합니다
|
||||
|
||||
### 🚀 step3
|
||||
|
||||
- 추가 기능(어드민에서 쿠폰 및 환영 메시지를 보낼 수 있는 기능이 있다.)
|
||||
- `@EventListener` 어노테이션을 활용해 코드를 변경 해보자.
|
||||
- > 스프링 4.2 부터 ApplicationEvent 를 상속 받아 객체를 생성하지 않아도 이벤트 객체 처럼 활용할 수 있다. `ApplicationListenerMethodAdapter` 객체에서 어노테이션을 찾아서 실행
|
||||
- 어드민에 알람을 보내는 중에 예외처리를 해보자
|
||||
- > `@TransactionalEventListener` 를 활용해 트랜잭션 단위를 제어해보자.
|
||||
- 비동기 활용
|
||||
- > `@EnableAsync` 와 `@Async` 를 활용해 비동기 처리를 해보자.
|
||||
|
||||
### 🚀 step4
|
||||
|
||||
- Domain Event
|
||||
- > AbstractAggregateRoot 를 상속 받아 이벤트를 제공
|
||||
- > registerEvent 를 통해 jpa의 save 를 명시적으로 할 때 마다 이벤트를 발행
|
||||
|
||||
---
|
||||
|
||||
#### 출처 : https://github.com/tongnamuu/SpringEvent
|
||||
24
놀이터(예제 코드 작성)/spring-event/README.md
Normal file
24
놀이터(예제 코드 작성)/spring-event/README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# 프로젝트 세팅 #
|
||||
|
||||
Java 11을 사용합니다.
|
||||
|
||||
처음부터 세팅하고 싶다면
|
||||

|
||||
|
||||
이후 annotation processing 옵션을 켜주세요
|
||||

|
||||
|
||||
이후 프로젝트 repository의 커밋을 따라오시면 그대로 실습하실 수 있습니다.
|
||||
|
||||
# 우리가 실습해볼 것 #
|
||||
|
||||
- 회원 가입 api를 이벤트를 활용해 개선해 봅니다.
|
||||
- 회원가입 플로우는 아래와 같습니다.
|
||||
- 회원가입을 하면 유저를 저장합니다
|
||||
- 알람이 나갑니다
|
||||
- 쿠폰을 발급해 줍니다
|
||||
- 이메일과 SMS로 환영 메시지를 보냅니다
|
||||
|
||||
---
|
||||
|
||||
#### 출처 : https://github.com/tongnamuu/SpringEvent
|
||||
46
놀이터(예제 코드 작성)/spring-event/build.gradle.kts
Normal file
46
놀이터(예제 코드 작성)/spring-event/build.gradle.kts
Normal file
@@ -0,0 +1,46 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("org.springframework.boot") version "2.6.1"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
kotlin("jvm") version "1.6.0"
|
||||
kotlin("plugin.spring") version "1.6.0"
|
||||
kotlin("plugin.jpa") version "1.6.0"
|
||||
}
|
||||
|
||||
group = "com.banjjoknim"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
java.sourceCompatibility = JavaVersion.VERSION_11
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
|
||||
runtimeOnly("com.h2database:h2")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = listOf("-Xjsr305=strict")
|
||||
jvmTarget = "11"
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.named("jar") {
|
||||
enabled = false
|
||||
}
|
||||
BIN
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
놀이터(예제 코드 작성)/spring-event/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
놀이터(예제 코드 작성)/spring-event/gradlew
vendored
Executable file
234
놀이터(예제 코드 작성)/spring-event/gradlew
vendored
Executable file
@@ -0,0 +1,234 @@
|
||||
#!/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/master/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
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# 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"'
|
||||
|
||||
# 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
|
||||
which java >/dev/null 2>&1 || 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
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
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
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
89
놀이터(예제 코드 작성)/spring-event/gradlew.bat
vendored
Normal file
89
놀이터(예제 코드 작성)/spring-event/gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@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=.
|
||||
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%" == "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%"=="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!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
BIN
놀이터(예제 코드 작성)/spring-event/images/img.png
Normal file
BIN
놀이터(예제 코드 작성)/spring-event/images/img.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
BIN
놀이터(예제 코드 작성)/spring-event/images/img_1.png
Normal file
BIN
놀이터(예제 코드 작성)/spring-event/images/img_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
1
놀이터(예제 코드 작성)/spring-event/settings.gradle.kts
Normal file
1
놀이터(예제 코드 작성)/spring-event/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "springEvent"
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class SpringEventApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<SpringEventApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.banjjoknim.playground.common
|
||||
|
||||
import org.springframework.http.HttpHeaders
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice
|
||||
import org.springframework.web.context.request.WebRequest
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
|
||||
|
||||
@RestControllerAdvice
|
||||
class ExceptionHandler : ResponseEntityExceptionHandler() {
|
||||
override fun handleMethodArgumentNotValid(
|
||||
ex: MethodArgumentNotValidException,
|
||||
headers: HttpHeaders,
|
||||
status: HttpStatus,
|
||||
request: WebRequest
|
||||
): ResponseEntity<Any> {
|
||||
logger.error("message", ex)
|
||||
val errors = ex.fieldErrors.map { fieldError ->
|
||||
mapOf(
|
||||
("propertyName" to fieldError.field),
|
||||
("reason" to fieldError.defaultMessage)
|
||||
)
|
||||
}
|
||||
return ResponseEntity.badRequest().body(errors)
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = [NoSuchElementException::class])
|
||||
fun handleNoSuchElement(ex: NoSuchElementException): ResponseEntity<String> {
|
||||
logger.error("message", ex)
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.message)
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = [Exception::class])
|
||||
fun handleException(ex: Exception): ResponseEntity<String> {
|
||||
logger.error("message", ex)
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.banjjoknim.playground.config
|
||||
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.scheduling.annotation.EnableAsync
|
||||
|
||||
/**
|
||||
* ```
|
||||
* @EnableAsync 어노테이션을 이용해서 비동기 설정을 활성화할 수 있다.
|
||||
*
|
||||
* 비동기 설정을 활성화했다면, 비동기로 실행할 이벤트 리스너에 @Async 어노테이션을 붙이면 된다.
|
||||
* ```
|
||||
*
|
||||
* @see EnableAsync
|
||||
* @see Async
|
||||
*/
|
||||
@EnableAsync
|
||||
@Configuration
|
||||
class AsyncConfiguration {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground.domain.admin
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@Service
|
||||
class AdminService {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun alarm(username: String) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", username)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground.domain.admin
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@Service
|
||||
class CouponService {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun registerCoupon(email: String) {
|
||||
log.info("쿠폰 등록 완료 : {}", email)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.data.domain.AbstractAggregateRoot
|
||||
import javax.persistence.Entity
|
||||
import javax.persistence.GeneratedValue
|
||||
import javax.persistence.GenerationType
|
||||
import javax.persistence.Id
|
||||
|
||||
/**
|
||||
* ```
|
||||
* AbstractAggregateRoot<T> 를 이용하면 쉽게 이벤트를 구현할 수 있다.
|
||||
*
|
||||
* 단, 명시적으로 AggregateRootRepository<T, ID> 에서 save()가 호출되어야 이벤트가 발행된다.
|
||||
* ```
|
||||
* @see AbstractAggregateRoot
|
||||
*/
|
||||
@Entity
|
||||
class AggregateRootUser(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long = 0L
|
||||
) : AbstractAggregateRoot<AggregateRootUser>() {
|
||||
|
||||
// AggregateRootUser Entity를 사용하는 AggregateRootUserRepository 에서 명시적으로 save() 가 호출되면 이벤트가 발행된다.
|
||||
fun publishAggregateRootEvent() {
|
||||
super.registerEvent(AggregateRootEvent("colt"))
|
||||
}
|
||||
|
||||
data class AggregateRootEvent(val name: String)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.event.EventListener
|
||||
import org.springframework.scheduling.annotation.Async
|
||||
import org.springframework.stereotype.Component
|
||||
import org.springframework.transaction.event.TransactionPhase
|
||||
import org.springframework.transaction.event.TransactionalEventListener
|
||||
|
||||
/**
|
||||
* ```
|
||||
* 기존에는 이벤트 리스너를 사용하기 위해서 ApplicationListener<T> 를 상속(또는 구현)해서 사용해야 했기에, 이벤트가 상속에 종속적이 되어 문제가 될 수 있었다.
|
||||
*
|
||||
* 하지만 스프링 4.2부터는 이벤트 리스너의 이벤트 처리를 어노테이션 기반으로 작성할 수 있도록 개선되었다.
|
||||
*
|
||||
* ApplicationListenerMethodAdapter 객체가 @EventListener 어노테이션을 찾아서 실행시켜준다.
|
||||
*
|
||||
* 빈 단위로 정의된 리스너(ApplicationListener<T> 를 상속하고 Component 로 등록된)에 대해서는 구현체로 SimpleApplicationEventMulticaster 를 사용한다. SimpleApplicationEventMulticaster 는 빈 단위로 정의된 작업을 실행시켜준다.
|
||||
*
|
||||
* 리스너는 메소드 단위로도 정의할 수 있다. 메소드에 @EventListener 어노테이션을 붙이면 이때는 구현체로 ApplicationListenerMethodAdapter 를 사용한다(구현체가 변경된다).
|
||||
* ```
|
||||
*
|
||||
* @see AbstractApplicationContext
|
||||
* @see ApplicationListenerMethodAdapter
|
||||
* @see SimpleApplicationEventMulticaster
|
||||
* @see ApplicationListenerMethodAdapter
|
||||
* @see EventListener(org.springframework.context.event)
|
||||
*/
|
||||
|
||||
@Component
|
||||
class AdminAnnotationEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: AdminAnnotationEvent) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponAnnotationEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: CouponAnnotationEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderAnnotationEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun handleEmail(event: SenderAnnotationEvent) {
|
||||
log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
}
|
||||
|
||||
@EventListener
|
||||
fun handleSMS(event: SenderAnnotationEvent) {
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 트랜잭션 단위를 이벤트에서 관리(제어)하기 위해서 @TransactionalEventListener 를 사용할 수 있다.
|
||||
*
|
||||
* 기본 설정은 TransactionPhase.AFTER_COMMIT 이다. 이 외에도 여러 상태가 있으니 참고하여 설계하는데 사용하도록 하자.
|
||||
*
|
||||
* @see TransactionalEventListener
|
||||
*/
|
||||
|
||||
@Component
|
||||
class AdminTransactionalEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: AdminTransactionalEvent) {
|
||||
throw RuntimeException()
|
||||
// log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponTransactionalEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
/**
|
||||
* 아래의 @TransactionalEventListener 로 인해
|
||||
*
|
||||
* 트랜잭션 커밋이 정상적으로 성공한 이후에 이벤트가 실행(처리)된다.
|
||||
*/
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||
fun onApplicationEvent(event: CouponTransactionalEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderTransactionalEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun handleEmail(event: SenderTransactionalEvent) {
|
||||
log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
}
|
||||
|
||||
@EventListener
|
||||
fun handleSMS(event: SenderTransactionalEvent) {
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class AdminAsyncEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: AdminAsyncEvent) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponAsyncEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@EventListener
|
||||
fun onApplicationEvent(event: CouponAsyncEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderAsyncEventListener {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
/**
|
||||
* 비동기로 설정하기 위해 @Async 어노테이션을 붙였다.
|
||||
*
|
||||
* 비동기로 설정했기 때문에 다른 쓰레드에서 이벤트가 실행된다.
|
||||
*
|
||||
* 그에 따라 예외가 발생해도 나머지 로직(회원 저장, 이벤트)은 제대로 처리된다(다른 쓰레드에서 예외가 발생한 것이기 때문에).
|
||||
*
|
||||
*/
|
||||
@Async
|
||||
@EventListener
|
||||
fun handleEmail(event: SenderAsyncEvent) {
|
||||
throw RuntimeException()
|
||||
// log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
}
|
||||
|
||||
/**
|
||||
* 비동기로 설정하기 위해 @Async 어노테이션을 붙였다.
|
||||
*
|
||||
* 비동기로 설정했기 때문에 다른 쓰레드에서 이벤트가 실행된다.
|
||||
*/
|
||||
@Async
|
||||
@EventListener
|
||||
fun handleSMS(event: SenderAsyncEvent) {
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
/**
|
||||
* 어노테이션을 사용한 이벤트
|
||||
*
|
||||
* 어노테이션을 사용하면 상속을 받지 않아도 되기 때문에 스프링에 대한 의존성이 제거된 순수한 자바 객체를 이벤트 객체로 사용할 수 있다.
|
||||
*
|
||||
* @see EventListener
|
||||
*/
|
||||
|
||||
class AdminAnnotationEvent(val username: String)
|
||||
|
||||
class CouponAnnotationEvent(val email: String)
|
||||
|
||||
class SenderAnnotationEvent(val email: String, val phoneNumber: String)
|
||||
|
||||
class AdminTransactionalEvent(val username: String)
|
||||
|
||||
class CouponTransactionalEvent(val email: String)
|
||||
|
||||
class SenderTransactionalEvent(val email: String, val phoneNumber: String)
|
||||
|
||||
class AdminAsyncEvent(val username: String)
|
||||
|
||||
class CouponAsyncEvent(val email: String)
|
||||
|
||||
class SenderAsyncEvent(val email: String, val phoneNumber: String)
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.ApplicationListener
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
/**
|
||||
* 상속 기반 이벤트 리스너
|
||||
*
|
||||
* 스프링의 컨텍스트를 사용하기 때문에 빈으로 등록해줘야 사용할 수 있다
|
||||
*
|
||||
* @see ApplicationListener
|
||||
*/
|
||||
|
||||
@Component
|
||||
class AdminInheritanceEventListener : ApplicationListener<AdminInheritanceEvent> {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun onApplicationEvent(event: AdminInheritanceEvent) {
|
||||
log.info("어드민 서비스 : {}님이 가입했습니다.", event.username)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class CouponInheritanceEventListener : ApplicationListener<CouponInheritanceEvent> {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun onApplicationEvent(event: CouponInheritanceEvent) {
|
||||
log.info("쿠폰 등록 완료 : {}", event.email)
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
class SenderInheritanceEventListener : ApplicationListener<SenderInheritanceEvent> {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun onApplicationEvent(event: SenderInheritanceEvent) {
|
||||
log.info("환영 이메일 발송 성공 : {}", event.email)
|
||||
log.info("환영 SMS 발송 성공 : {}", event.phoneNumber)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.springframework.context.ApplicationEvent
|
||||
|
||||
/**
|
||||
* 상속 기반 이벤트
|
||||
*
|
||||
* ApplicationEvent 를 상속받아서 사용한다.
|
||||
*
|
||||
* @see ApplicationEvent
|
||||
*/
|
||||
|
||||
class AdminInheritanceEvent(source: Any, val username: String) : ApplicationEvent(source)
|
||||
|
||||
class CouponInheritanceEvent(source: Any, val email: String) : ApplicationEvent(source)
|
||||
|
||||
class SenderInheritanceEvent(source: Any, val email: String, val phoneNumber: String) : ApplicationEvent(source)
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.banjjoknim.playground.domain.event
|
||||
|
||||
import org.hibernate.SessionFactory
|
||||
import org.hibernate.event.service.spi.EventListenerRegistry
|
||||
import org.hibernate.event.spi.EventType
|
||||
import org.hibernate.event.spi.PostInsertEvent
|
||||
import org.hibernate.event.spi.PostInsertEventListener
|
||||
import org.hibernate.internal.SessionFactoryImpl
|
||||
import org.hibernate.persister.entity.EntityPersister
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
/**
|
||||
* ```
|
||||
* org.hibernate.event.spi.EventType 을 살펴보면, 다양한 이벤트 발행시점(상태)을 볼 수 있다.
|
||||
*
|
||||
* 다양한 이벤트 발행시점(상태)과 이벤트를 이용해서 비즈니스 로직을 처리할 수 있다.
|
||||
*
|
||||
* 이벤트를 심도있게, 더 잘 활용하고 싶다면 Hibernate Session Event (Hibernate Event Session) 를 공부하도록 하자.
|
||||
*
|
||||
* Hibernate Session 의 이벤트 인터셉트를 이용해서 다양하게 활용할 수 있다.
|
||||
* ```
|
||||
* @see EventType
|
||||
*/
|
||||
@Component
|
||||
class DomainEvent {
|
||||
|
||||
private lateinit var sessionFactory: SessionFactory
|
||||
|
||||
fun sample() {
|
||||
val registry = (sessionFactory as SessionFactoryImpl).serviceRegistry.getService(EventListenerRegistry::class.java)
|
||||
registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(CustomEventListener())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
class CustomEventListener : PostInsertEventListener {
|
||||
override fun requiresPostCommitHanding(persister: EntityPersister?): Boolean {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override fun onPostInsert(event: PostInsertEvent?) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.banjjoknim.playground.domain.sender
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@Service
|
||||
class SenderService {
|
||||
private val log = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun sendEmail(email: String) {
|
||||
log.info("환영 이메일 발송 성공 : {}", email)
|
||||
}
|
||||
|
||||
fun sendSMS(phoneNumber: String) {
|
||||
log.info("환영 SMS 발송 성공 : {}", phoneNumber)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.event.AdminAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.AdminAsyncEvent
|
||||
import com.banjjoknim.playground.domain.event.AdminInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.AdminTransactionalEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponAsyncEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponTransactionalEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderAsyncEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderTransactionalEvent
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
import javax.persistence.Column
|
||||
import javax.persistence.Entity
|
||||
import javax.persistence.GeneratedValue
|
||||
import javax.persistence.GenerationType
|
||||
import javax.persistence.Id
|
||||
|
||||
@Entity
|
||||
class User(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = 0L,
|
||||
|
||||
@Column(name = "name")
|
||||
val name: String = "",
|
||||
|
||||
@Column(name = "email")
|
||||
val email: String = "",
|
||||
|
||||
@Column(name = "phoneNumber")
|
||||
val phoneNumber: String = ""
|
||||
) {
|
||||
/**
|
||||
* 상속 기반의 이벤트 사용
|
||||
*/
|
||||
fun publishInheritanceEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
publishInheritanceAdminEvent(eventPublisher)
|
||||
publishInheritanceCouponEvent(eventPublisher)
|
||||
publishInheritanceSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishInheritanceAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminInheritanceEvent(this, name))
|
||||
}
|
||||
|
||||
private fun publishInheritanceCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponInheritanceEvent(this, email))
|
||||
}
|
||||
|
||||
private fun publishInheritanceSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderInheritanceEvent(this, email, phoneNumber))
|
||||
}
|
||||
|
||||
fun publishAnnotationEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
publishAnnotationAdminEvent(eventPublisher)
|
||||
publishAnnotationCouponEvent(eventPublisher)
|
||||
publishAnnotationSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishAnnotationAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminAnnotationEvent(name))
|
||||
}
|
||||
|
||||
private fun publishAnnotationCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponAnnotationEvent(email))
|
||||
}
|
||||
|
||||
private fun publishAnnotationSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderAnnotationEvent(email, phoneNumber))
|
||||
}
|
||||
|
||||
fun publishWithTransactionalEventListener(eventPublisher: ApplicationEventPublisher) {
|
||||
publishWithTransactionalCouponEvent(eventPublisher)
|
||||
publishWithTransactionalAdminEvent(eventPublisher)
|
||||
publishWithTransactionalSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishWithTransactionalAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminTransactionalEvent(name))
|
||||
}
|
||||
|
||||
private fun publishWithTransactionalCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponTransactionalEvent(email))
|
||||
}
|
||||
|
||||
private fun publishWithTransactionalSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderTransactionalEvent(email, phoneNumber))
|
||||
}
|
||||
|
||||
fun publishWithAsyncEventListener(eventPublisher: ApplicationEventPublisher) {
|
||||
publishWithAsyncCouponEvent(eventPublisher)
|
||||
publishWithAsyncAdminEvent(eventPublisher)
|
||||
publishWithAsyncSenderEvent(eventPublisher)
|
||||
}
|
||||
|
||||
private fun publishWithAsyncAdminEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(AdminAsyncEvent(name))
|
||||
}
|
||||
|
||||
private fun publishWithAsyncCouponEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(CouponAsyncEvent(email))
|
||||
}
|
||||
|
||||
private fun publishWithAsyncSenderEvent(eventPublisher: ApplicationEventPublisher) {
|
||||
eventPublisher.publishEvent(SenderAsyncEvent(email, phoneNumber))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.http.ResponseEntity
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.PathVariable
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import javax.validation.Valid
|
||||
|
||||
@RequestMapping("/users")
|
||||
@RestController
|
||||
class UserApi(
|
||||
private val userService: UserService,
|
||||
private val userServiceBaseOnInheritanceEvent: UserServiceBaseOnInheritanceEvent,
|
||||
private val userServiceBaseOnAnnotationEvent: UserServiceBaseOnAnnotationEvent
|
||||
) {
|
||||
/**
|
||||
* 의존성을 모두 갖고 서비스 내에서 서비스를 호출하는 방식
|
||||
*/
|
||||
@PostMapping("")
|
||||
fun createUser(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userService.createUser(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 상속 기반의 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/inheritance")
|
||||
fun createUserWithInheritanceEvent(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnInheritanceEvent.createUser(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 어노테이션 기반의 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/annotation")
|
||||
fun createUserWithAnnotationEvent(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnAnnotationEvent.createUser(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 트랜잭션 이벤트 리스너 어노테이션을 이용한 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/transactional")
|
||||
fun createUserWithTransactionalEventListener(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnAnnotationEvent.createUserWithTransactionalEventListener(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 비동기 이벤트 리스너를 이용한 이벤트 사용 방식
|
||||
*/
|
||||
@PostMapping("/async")
|
||||
fun createUserWithAsyncEventListener(@RequestBody @Valid request: CreateUserRequest): ResponseEntity<Unit> {
|
||||
userServiceBaseOnAnnotationEvent.createUserWithAsyncEventListener(request)
|
||||
return ResponseEntity.ok().build()
|
||||
}
|
||||
|
||||
@GetMapping("/{userId}")
|
||||
fun retrieveUser(@PathVariable userId: Long): ResponseEntity<RetrieveUserResponse> {
|
||||
val response = userService.retrieveUser(userId)
|
||||
return ResponseEntity.ok(response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import javax.validation.constraints.NotBlank
|
||||
|
||||
data class CreateUserRequest(
|
||||
@field:NotBlank(message = "이름을 입력해주세요")
|
||||
val name: String = "",
|
||||
@field:NotBlank(message = "이메일을 입력해주세요")
|
||||
val email: String = "",
|
||||
@field:NotBlank(message = "휴대폰 번호를 입력해주세요")
|
||||
val phoneNumber: String = ""
|
||||
) {
|
||||
fun toUser(): User {
|
||||
return User(name = name, email = email, phoneNumber = phoneNumber)
|
||||
}
|
||||
}
|
||||
|
||||
data class RetrieveUserResponse(
|
||||
val name: String,
|
||||
val email: String,
|
||||
val phoneNumber: String
|
||||
) {
|
||||
constructor(user: User) : this(user.name, user.email, user.phoneNumber)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
|
||||
interface UserRepository : JpaRepository<User, Long> {
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.admin.AdminService
|
||||
import com.banjjoknim.playground.domain.admin.CouponService
|
||||
import com.banjjoknim.playground.domain.sender.SenderService
|
||||
import org.springframework.data.repository.findByIdOrNull
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
/**
|
||||
* 의존성을 모두 갖고 서비스 내에서 서비스를 호출하는 방식
|
||||
*/
|
||||
@Transactional
|
||||
@Service
|
||||
class UserService(
|
||||
private val userRepository: UserRepository,
|
||||
private val adminService: AdminService,
|
||||
private val senderService: SenderService,
|
||||
private val couponService: CouponService
|
||||
) {
|
||||
fun createUser(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
adminService.alarm(user.name)
|
||||
couponService.registerCoupon(user.email)
|
||||
senderService.sendSMS(user.phoneNumber)
|
||||
senderService.sendEmail(user.email)
|
||||
}
|
||||
|
||||
fun retrieveUser(userId: Long): RetrieveUserResponse {
|
||||
val user = userRepository.findByIdOrNull(userId)
|
||||
?: throw NoSuchElementException("회원이 존재하지 않습니다. [userId: $userId]")
|
||||
return RetrieveUserResponse(user)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
@Transactional
|
||||
@Service
|
||||
class UserServiceBaseOnAnnotationEvent(
|
||||
private val userRepository: UserRepository,
|
||||
private val eventPublisher: ApplicationEventPublisher
|
||||
) {
|
||||
fun createUser(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishAnnotationEvent(eventPublisher)
|
||||
}
|
||||
|
||||
fun createUserWithTransactionalEventListener(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishWithTransactionalEventListener(eventPublisher)
|
||||
}
|
||||
|
||||
fun createUserWithAsyncEventListener(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishWithAsyncEventListener(eventPublisher)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
/**
|
||||
* 상속 기반의 이벤트를 사용하는 서비스
|
||||
*
|
||||
* @see BaseOnInheritanceEventListeners
|
||||
* @see BaseOnInheritanceEvents
|
||||
*/
|
||||
@Transactional
|
||||
@Service
|
||||
class UserServiceBaseOnInheritanceEvent(
|
||||
private val userRepository: UserRepository,
|
||||
private val eventPublisher: ApplicationEventPublisher
|
||||
) {
|
||||
fun createUser(request: CreateUserRequest) {
|
||||
val user = request.toUser()
|
||||
userRepository.save(user)
|
||||
user.publishInheritanceEvent(eventPublisher)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
### 고전적인 방식
|
||||
POST http://localhost:8080/users
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 상속 기반의 이벤트를 사용하는 방식
|
||||
POST http://localhost:8080/users/inheritance
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 어노테이션 기반의 이벤트를 사용하는 방식
|
||||
POST http://localhost:8080/users/annotation
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 트랜잭션 이벤트 리스너 어노테이션을 사용하는 방식
|
||||
POST http://localhost:8080/users/transactional
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
### 비동기 이벤트 리스너 어노테이션을 사용하는 방식
|
||||
POST http://localhost:8080/users/async
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "banjjoknim",
|
||||
"email": "banjjoknim@github.com",
|
||||
"phoneNumber": "010-1234-5678"
|
||||
}
|
||||
|
||||
###
|
||||
GET http://localhost:8080/users/1
|
||||
@@ -0,0 +1,19 @@
|
||||
spring:
|
||||
|
||||
h2:
|
||||
console:
|
||||
enabled: true
|
||||
|
||||
datasource:
|
||||
driver-class-name: org.h2.Driver
|
||||
username: sa
|
||||
password:
|
||||
url: jdbc:h2:mem:testdb;MODE=MySQL;
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create-drop
|
||||
show-sql: true
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
|
||||
@SpringBootTest
|
||||
class SpringEventApplicationTests {
|
||||
|
||||
@Test
|
||||
fun contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.event.AdminAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponAnnotationEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderAnnotationEvent
|
||||
import org.assertj.core.api.Assertions
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.mockito.ArgumentCaptor
|
||||
import org.mockito.BDDMockito
|
||||
import org.mockito.Captor
|
||||
import org.mockito.Mock
|
||||
import org.mockito.junit.jupiter.MockitoExtension
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
|
||||
@ExtendWith(MockitoExtension::class)
|
||||
class UserServiceBaseOnAnnotationEventTest {
|
||||
|
||||
@Mock
|
||||
private lateinit var userRepository: UserRepository
|
||||
|
||||
@Mock
|
||||
private lateinit var eventPublisher: ApplicationEventPublisher
|
||||
|
||||
/**
|
||||
* 발행된 이벤트를 캡쳐해서 데이터를 저장할 수 있다.
|
||||
*
|
||||
* 이때, 순수한 자바 객체를 이벤트 객체로 사용하므로 ArgumentCaptor 의 제네릭을 제네릭을 Any(Object)로 지정한다.
|
||||
*/
|
||||
@Captor
|
||||
private lateinit var eventPublisherCaptor: ArgumentCaptor<Any>
|
||||
|
||||
private lateinit var userServiceBaseOnAnnotationEvent: UserServiceBaseOnAnnotationEvent
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
userServiceBaseOnAnnotationEvent = UserServiceBaseOnAnnotationEvent(userRepository, eventPublisher)
|
||||
}
|
||||
|
||||
/**
|
||||
* 아래와 같이 테스트는 작성할 수 있지만, 통합테스트를 돌려야 실제로 이벤트가 발행되고 이벤트 리스너가 이벤트를 처리하는 것을 확인할 수 있다는 한계점이 있다.
|
||||
*/
|
||||
@Test
|
||||
fun `회원 생성시 이벤트의 총 발행 횟수와 각각의 이벤트의 타입을 검사한다`() {
|
||||
BDDMockito.given(userRepository.save(BDDMockito.any()))
|
||||
.willReturn(User(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678"))
|
||||
val request =
|
||||
CreateUserRequest(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678")
|
||||
|
||||
userServiceBaseOnAnnotationEvent.createUser(request)
|
||||
|
||||
BDDMockito.then(eventPublisher).should(BDDMockito.times(3)).publishEvent(eventPublisherCaptor.capture())
|
||||
// 캡쳐한 이벤트는 순차적으로 저장되므로 아래와 같이 검증할 수도 있다.
|
||||
val events = eventPublisherCaptor.allValues
|
||||
Assertions.assertThat(events[0]).isInstanceOf(AdminAnnotationEvent::class.java)
|
||||
Assertions.assertThat(events[1]).isInstanceOf(CouponAnnotationEvent::class.java)
|
||||
Assertions.assertThat(events[2]).isInstanceOf(SenderAnnotationEvent::class.java)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.banjjoknim.playground.domain.user
|
||||
|
||||
import com.banjjoknim.playground.domain.event.AdminInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.CouponInheritanceEvent
|
||||
import com.banjjoknim.playground.domain.event.SenderInheritanceEvent
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.mockito.ArgumentCaptor
|
||||
import org.mockito.BDDMockito.any
|
||||
import org.mockito.BDDMockito.given
|
||||
import org.mockito.BDDMockito.then
|
||||
import org.mockito.BDDMockito.times
|
||||
import org.mockito.Captor
|
||||
import org.mockito.Mock
|
||||
import org.mockito.junit.jupiter.MockitoExtension
|
||||
import org.springframework.context.ApplicationEvent
|
||||
import org.springframework.context.ApplicationEventPublisher
|
||||
|
||||
@ExtendWith(MockitoExtension::class)
|
||||
class UserServiceBaseOnInheritanceEventTest {
|
||||
|
||||
@Mock
|
||||
private lateinit var userRepository: UserRepository
|
||||
|
||||
@Mock
|
||||
private lateinit var eventPublisher: ApplicationEventPublisher
|
||||
|
||||
/**
|
||||
* 발행된 이벤트를 캡쳐해서 데이터를 저장할 수 있다.
|
||||
*
|
||||
* 이때, ApplicationEvent 를 상속받은 객체를 이벤트 객체로 사용하므로 ArgumentCaptor 의 제네릭을 ApplicationEvent 로 지정한다.
|
||||
*/
|
||||
@Captor
|
||||
private lateinit var eventPublisherCaptor: ArgumentCaptor<ApplicationEvent>
|
||||
|
||||
private lateinit var userServiceBaseOnInheritanceEvent: UserServiceBaseOnInheritanceEvent
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
userServiceBaseOnInheritanceEvent = UserServiceBaseOnInheritanceEvent(userRepository, eventPublisher)
|
||||
}
|
||||
|
||||
/**
|
||||
* 아래와 같이 테스트는 작성할 수 있지만, 통합테스트를 돌려야 실제로 이벤트가 발행되고 이벤트 리스너가 이벤트를 처리하는 것을 확인할 수 있다는 한계점이 있다.
|
||||
*/
|
||||
@Test
|
||||
fun `회원 생성시 이벤트의 총 발행 횟수와 각각의 이벤트의 타입을 검사한다`() {
|
||||
given(userRepository.save(any()))
|
||||
.willReturn(User(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678"))
|
||||
val request =
|
||||
CreateUserRequest(name = "banjjoknim", email = "banjjoknim@github.com", phoneNumber = "010-1234-5678")
|
||||
|
||||
userServiceBaseOnInheritanceEvent.createUser(request)
|
||||
|
||||
then(eventPublisher).should(times(3)).publishEvent(eventPublisherCaptor.capture())
|
||||
// 캡쳐한 이벤트는 순차적으로 저장되므로 아래와 같이 검증할 수도 있다.
|
||||
val events = eventPublisherCaptor.allValues
|
||||
assertThat(events[0]).isInstanceOf(AdminInheritanceEvent::class.java)
|
||||
assertThat(events[1]).isInstanceOf(CouponInheritanceEvent::class.java)
|
||||
assertThat(events[2]).isInstanceOf(SenderInheritanceEvent::class.java)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user