├── .gitignore ├── .travis.yml ├── README.md ├── email-service ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── emailservice │ │ │ ├── AppRunner.java │ │ │ ├── EmailServiceApplication.java │ │ │ ├── domain │ │ │ ├── email │ │ │ │ └── service │ │ │ │ │ ├── EmailSender.java │ │ │ │ │ └── EmailService.java │ │ │ └── user │ │ │ │ ├── model │ │ │ │ └── User.java │ │ │ │ └── service │ │ │ │ └── UserService.java │ │ │ ├── infrastructure │ │ │ └── config │ │ │ │ ├── AsyncConfig.java │ │ │ │ ├── RestTemplateConfig.java │ │ │ │ └── SwaggerConfig.java │ │ │ └── rest │ │ │ └── controller │ │ │ └── email │ │ │ └── EmailController.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── emailservice │ ├── domain │ ├── email │ │ └── service │ │ │ ├── EmailSenderTest.groovy │ │ │ └── EmailServiceTest.groovy │ └── user │ │ └── service │ │ └── UserServiceTest.groovy │ └── rest │ └── controller │ └── email │ ├── EmailControllerIntegrationTest.java │ └── EmailControllerTestHealthCheckTest.java ├── pom.xml └── slow-user-service ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── slowuserservice │ │ ├── SlowUserServiceApplication.java │ │ ├── domain │ │ └── user │ │ │ ├── model │ │ │ └── User.java │ │ │ └── service │ │ │ └── UserService.java │ │ ├── infrastructure │ │ ├── database │ │ │ └── UsersDatabaseMock.java │ │ ├── exception │ │ │ └── UserNotFoundException.java │ │ ├── repository │ │ │ └── UserRepository.java │ │ └── utils │ │ │ └── ThreadUtils.java │ │ └── rest │ │ └── controller │ │ └── user │ │ └── UserController.java └── resources │ └── application.properties └── test └── java └── com └── example └── slowuserservice ├── domain └── user │ └── service │ └── UserServiceTest.groovy └── rest └── controller └── user ├── UserControllerHealthCheckTest.java ├── UserControllerIntegrationTest.java └── UserControllerTest.groovy /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Java template 3 | # Compiled class file 4 | *.class 5 | 6 | # Log file 7 | *.log 8 | 9 | # BlueJ files 10 | *.ctxt 11 | 12 | # Mobile Tools for Java (J2ME) 13 | .mtj.tmp/ 14 | 15 | # Package Files # 16 | *.jar 17 | *.war 18 | *.nar 19 | *.ear 20 | *.zip 21 | *.tar.gz 22 | *.rar 23 | 24 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 25 | hs_err_pid* 26 | 27 | .idea/ 28 | spring-boot-async.iml 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://app.travis-ci.com/mtumilowicz/spring-boot-async.svg?branch=master)](https://app.travis-ci.com/mtumilowicz/spring-boot-async) 2 | 3 | # spring-boot-async 4 | The main goal of this project is to explore basic features of `@Async` 5 | spring annotation and compare results with non-concurrent approach. 6 | 7 | * references 8 | * https://spring.io/guides/gs/async-method/ 9 | * http://www.baeldung.com/spring-async 10 | * [Concurrency in Spring Boot Applications: Making the Right Choice by Andrei Shakirin](https://www.youtube.com/watch?v=vhHDlSV_0zg) 11 | 12 | # preface 13 | This project shows how to create asynchronous queries using Spring. 14 | 15 | Our approach is to run expensive jobs in the background and wait 16 | for the results using Java’s `CompletableFuture` interface. 17 | 18 | * spring boot concurrency options 19 | * java executors and futures 20 | * completable futures 21 | * @Async annotation 22 | * reactive programming 23 | * virtual threads 24 | * structured concurrency 25 | 26 | # manual 27 | 1. Enable asynchronous support: 28 | ``` 29 | @Configuration 30 | @EnableAsync 31 | class AsyncConfig { 32 | @Bean 33 | Executor asyncExecutor() { 34 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 35 | executor.setCorePoolSize(4); 36 | executor.setMaxPoolSize(4); 37 | executor.setQueueCapacity(500); 38 | executor.setThreadNamePrefix("EmailSender-"); 39 | executor.initialize(); 40 | return executor; 41 | } 42 | } 43 | ``` 44 | _Remark_: `asyncExecutor()` is used to customize default behaviour 45 | and is not mandatory. 46 | 1. Annotate method with `@Async`, and set return type to `CompletableFuture` 47 | where `XXX` is a wanted return type, for example: 48 | ``` 49 | String customMethod() { 50 | ... 51 | } 52 | ``` 53 | should be transformed to: 54 | ``` 55 | CompletableFuture customMethod() { 56 | ... 57 | } 58 | ``` 59 | 1. Consume it with `Completable API`, for example: 60 | * `CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[]{})).join();` 61 | * `CompletableFuture.allOf(completableFuture1, completableFuture2).join();` 62 | 63 | 1. Extract requested return (note that `get()` throws checked exception): 64 | * `XXX xxx = completableFuture.join()` 65 | 66 | # project description 67 | * `email-service` - microservice responsible for sending emails to given 68 | users 69 | * `EmailController` - REST controller; receives `login-message` map, 70 | then asks `slow-user-service` for `emails` and sends messages 71 | * in `EmailService` we have the same methods: 72 | * `@Async` method - `asyncSend` - concurrently sends messages 73 | * non-concurrent method - `send` 74 | * in `AppRunner` we simulate interactions and compare times 75 | * `slow-user-service` 76 | * `UserController` returns `User` bean (login, name, email...) 77 | for given login 78 | * in `UserRepository` we sleep thread for `user.repository.delay.seconds` 79 | (configurable in `application.properties`) and then return requested user 80 | 81 | # tests 82 | **Coverage**: `93%` 83 | -------------------------------------------------------------------------------- /email-service/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /email-service/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mtumilowicz/spring-boot-async/2d44f7deb1e0fc9337698cc8ba36394b82424b41/email-service/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /email-service/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /email-service/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /email-service/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /email-service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | email-service 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | email-service 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 2.9.2 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | org.projectlombok 36 | lombok 37 | true 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-test 42 | test 43 | 44 | 45 | com.google.guava 46 | guava 47 | 25.1-jre 48 | 49 | 50 | org.apache.commons 51 | commons-lang3 52 | 3.7 53 | 54 | 55 | org.spockframework 56 | spock-core 57 | 1.1-groovy-2.4 58 | test 59 | 60 | 61 | io.springfox 62 | springfox-swagger2 63 | ${swagger.version} 64 | 65 | 66 | io.springfox 67 | springfox-swagger-ui 68 | ${swagger.version} 69 | 70 | 71 | 72 | 73 | 74 | 75 | org.springframework.boot 76 | spring-boot-maven-plugin 77 | 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/AppRunner.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice; 2 | 3 | import com.example.emailservice.rest.controller.email.EmailController; 4 | import com.google.common.collect.ImmutableMap; 5 | import lombok.AllArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Created by mtumilowicz on 2018-07-28. 15 | */ 16 | @Component 17 | @AllArgsConstructor 18 | @Slf4j 19 | public class AppRunner implements CommandLineRunner { 20 | 21 | private final EmailController emailController; 22 | 23 | @Override 24 | public void run(String... args) { 25 | ImmutableMap loginMessageMap = ImmutableMap.of( 26 | "mtumilowicz", "4mtumilowicz", 27 | "hank", "4hank", 28 | "fjodor", "4fjodor", 29 | "ernie", "4ernie", 30 | "non-existing-user", "4non-existing-user" 31 | ); 32 | 33 | long start = System.currentTimeMillis(); 34 | ResponseEntity> test = emailController.asyncSend(loginMessageMap); 35 | log.info("Async Elapsed time: " + (System.currentTimeMillis() - start)); 36 | log.info("--> " + test.toString()); 37 | 38 | start = System.currentTimeMillis(); 39 | 40 | ResponseEntity> test2 = emailController.send(loginMessageMap); 41 | 42 | // Print results, including elapsed time 43 | log.info("Not-async Elapsed time: " + (System.currentTimeMillis() - start)); 44 | log.info("--> " + test2.toString()); 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/EmailServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class EmailServiceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(EmailServiceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/domain/email/service/EmailSender.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.email.service; 2 | 3 | import com.example.emailservice.domain.user.model.User; 4 | import com.google.common.base.Preconditions; 5 | import lombok.AccessLevel; 6 | import lombok.AllArgsConstructor; 7 | import lombok.NonNull; 8 | import lombok.experimental.FieldDefaults; 9 | import org.apache.commons.lang3.StringUtils; 10 | import org.springframework.stereotype.Service; 11 | 12 | import static java.util.Objects.nonNull; 13 | 14 | /** 15 | * Created by mtumilowicz on 2018-07-27. 16 | */ 17 | @Service 18 | @AllArgsConstructor 19 | @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) 20 | public class EmailSender { 21 | 22 | String send(@NonNull User user, @NonNull String message) { 23 | Preconditions.checkArgument(nonNull(user.getEmail())); 24 | 25 | return String.format("Email: {%s} was sent to: %s.", 26 | message, 27 | StringUtils.defaultIfEmpty(user.getLogin(), user.getEmail())); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/domain/email/service/EmailService.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.email.service; 2 | 3 | import com.example.emailservice.domain.user.service.UserService; 4 | import lombok.AccessLevel; 5 | import lombok.AllArgsConstructor; 6 | import lombok.NonNull; 7 | import lombok.experimental.FieldDefaults; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.scheduling.annotation.Async; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.util.concurrent.CompletableFuture; 13 | 14 | import static java.util.Objects.nonNull; 15 | 16 | /** 17 | * Created by mtumilowicz on 2018-07-28. 18 | */ 19 | @Service 20 | @AllArgsConstructor 21 | @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) 22 | @Slf4j 23 | public class EmailService { 24 | EmailSender sender; 25 | UserService userService; 26 | 27 | @Async 28 | public CompletableFuture asyncSend(@NonNull String login, @NonNull String message) { 29 | log.info("Sending " + message + " to: " + login); 30 | return CompletableFuture.supplyAsync(() -> sender.send(userService.getUserById(login), message)) 31 | .handle((ok, ex) -> nonNull(ok) ? 32 | ok : 33 | String.format("FAIL: Sending email {%s} to %s reason: %s", 34 | message, 35 | login, 36 | ex.getLocalizedMessage())); 37 | } 38 | 39 | public String send(@NonNull String login, @NonNull String message) { 40 | log.info("Sending " + message + " to: " + login); 41 | try { 42 | return sender.send(userService.getUserById(login), message); 43 | } catch (Exception t) { 44 | return String.format("FAIL: Sending email {%s} to %s reason: %s", 45 | message, 46 | login, 47 | t.getLocalizedMessage()); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/domain/user/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.user.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import lombok.Builder; 5 | import lombok.Value; 6 | 7 | /** 8 | * Created by mtumilowicz on 2018-07-28. 9 | */ 10 | @Value 11 | @Builder 12 | @JsonIgnoreProperties(ignoreUnknown=true) 13 | public class User { 14 | String login; 15 | String email; 16 | } 17 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/domain/user/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.user.service; 2 | 3 | import com.example.emailservice.domain.user.model.User; 4 | import lombok.AccessLevel; 5 | import lombok.AllArgsConstructor; 6 | import lombok.NonNull; 7 | import lombok.experimental.FieldDefaults; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.web.client.RestTemplate; 10 | 11 | /** 12 | * Created by mtumilowicz on 2018-07-28. 13 | */ 14 | @Service 15 | @AllArgsConstructor 16 | @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) 17 | public class UserService { 18 | 19 | RestTemplate restTemplate; 20 | 21 | public User getUserById(@NonNull String id) { 22 | return restTemplate.getForObject(String.format("http://localhost:8090/users/%s", id), User.class); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/infrastructure/config/AsyncConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.infrastructure.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.scheduling.annotation.EnableAsync; 6 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 7 | 8 | import java.util.concurrent.Executor; 9 | 10 | /** 11 | * Created by mtumilowicz on 2018-07-28. 12 | */ 13 | @Configuration 14 | @EnableAsync 15 | class AsyncConfig { 16 | 17 | @Bean 18 | Executor asyncExecutor() { 19 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 20 | executor.setCorePoolSize(4); 21 | executor.setMaxPoolSize(4); 22 | executor.setQueueCapacity(500); 23 | executor.setThreadNamePrefix("EmailSender-"); 24 | executor.initialize(); 25 | return executor; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/infrastructure/config/RestTemplateConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.infrastructure.config; 2 | 3 | import org.springframework.boot.web.client.RestTemplateBuilder; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | /** 9 | * Created by mtumilowicz on 2018-07-26. 10 | */ 11 | @Configuration 12 | class RestTemplateConfig { 13 | @Bean 14 | public RestTemplate restTemplate(RestTemplateBuilder builder) { 15 | return builder.build(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/infrastructure/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.infrastructure.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import springfox.documentation.builders.PathSelectors; 6 | import springfox.documentation.builders.RequestHandlerSelectors; 7 | import springfox.documentation.spi.DocumentationType; 8 | import springfox.documentation.spring.web.plugins.Docket; 9 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 10 | 11 | /** 12 | * Created by mtumilowicz on 2018-07-28. 13 | */ 14 | @Configuration 15 | @EnableSwagger2 16 | class SwaggerConfig { 17 | @Bean 18 | Docket api() { 19 | return new Docket(DocumentationType.SWAGGER_2) 20 | .select() 21 | .apis(RequestHandlerSelectors.any()) 22 | .paths(PathSelectors.any()) 23 | .build(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /email-service/src/main/java/com/example/emailservice/rest/controller/email/EmailController.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.rest.controller.email; 2 | 3 | import com.example.emailservice.domain.email.service.EmailService; 4 | import lombok.AccessLevel; 5 | import lombok.AllArgsConstructor; 6 | import lombok.experimental.FieldDefaults; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | import java.util.concurrent.CompletableFuture; 13 | import java.util.stream.Collectors; 14 | 15 | /** 16 | * Created by mtumilowicz on 2018-07-28. 17 | */ 18 | @RestController 19 | @AllArgsConstructor 20 | @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) 21 | @RequestMapping("emails") 22 | public class EmailController { 23 | 24 | EmailService emailService; 25 | 26 | // example json 27 | // { 28 | // "mtumilowicz": "4mtumilowicz", 29 | // "hank": "4hank", 30 | // "fjodor": "4fjodor", 31 | // "ernie": "4ernie", 32 | // "non-existing-user": "4non-existing-user" 33 | // } 34 | 35 | @PostMapping("send/async") 36 | public ResponseEntity> asyncSend(@RequestBody Map loginMessageMap) { 37 | List> completableFutures = loginMessageMap 38 | .entrySet() 39 | .stream() 40 | .map(entry -> emailService.asyncSend(entry.getKey(), entry.getValue())) 41 | .collect(Collectors.toList()); 42 | 43 | CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[]{})).join(); 44 | 45 | return ResponseEntity.ok(completableFutures 46 | .stream() 47 | .map(CompletableFuture::join) 48 | .collect(Collectors.toList())); 49 | } 50 | 51 | @PostMapping("send") 52 | public ResponseEntity> send(@RequestBody Map loginMessageMap) { 53 | return ResponseEntity.ok(loginMessageMap 54 | .entrySet() 55 | .stream() 56 | .map(entry -> emailService.send(entry.getKey(), entry.getValue())) 57 | .collect(Collectors.toList())); 58 | } 59 | 60 | @GetMapping("health") 61 | public void health() { 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /email-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mtumilowicz/spring-boot-async/2d44f7deb1e0fc9337698cc8ba36394b82424b41/email-service/src/main/resources/application.properties -------------------------------------------------------------------------------- /email-service/src/test/java/com/example/emailservice/domain/email/service/EmailSenderTest.groovy: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.email.service 2 | 3 | import com.example.emailservice.domain.user.model.User 4 | import spock.lang.Specification 5 | /** 6 | * Created by mtumilowicz on 2018-07-28. 7 | */ 8 | class EmailSenderTest extends Specification { 9 | def "test send - empty email"() { 10 | given: 11 | User user = User.builder().build() 12 | 13 | when: 14 | new EmailSender().send(user, '') 15 | 16 | then: 17 | thrown(IllegalArgumentException) 18 | } 19 | 20 | def "test send - empty login"() { 21 | given: 22 | User user = User.builder().email("a@a.pl").build() 23 | 24 | expect: 25 | new EmailSender().send(user, 'test') == "Email: {test} was sent to: a@a.pl." 26 | } 27 | 28 | def "test send - not empty login"() { 29 | given: 30 | User user = User.builder().login("a").email("a@a.pl").build() 31 | 32 | expect: 33 | new EmailSender().send(user, 'test') == "Email: {test} was sent to: a." 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /email-service/src/test/java/com/example/emailservice/domain/email/service/EmailServiceTest.groovy: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.email.service 2 | 3 | import com.example.emailservice.domain.user.model.User 4 | import com.example.emailservice.domain.user.service.UserService 5 | import spock.lang.Specification 6 | 7 | /** 8 | * Created by mtumilowicz on 2018-07-28. 9 | */ 10 | class EmailServiceTest extends Specification { 11 | def "asyncSend - without exception"() { 12 | given: 13 | def emailSender = new EmailSender() 14 | def userService = Mock(UserService) { 15 | getUserById(_) >> User.builder() 16 | .login(_login) 17 | .email("a@a.pl") 18 | .build() 19 | } 20 | 21 | and: 22 | def emailService = new EmailService(emailSender, userService) 23 | 24 | when: 25 | def send = emailService.asyncSend(_login, _message).join() 26 | 27 | then: 28 | send == "Email: {$_message} was sent to: $_login." 29 | 30 | where: 31 | _login | _message 32 | "login" | "message" 33 | } 34 | 35 | def "asyncSend - exception"() { 36 | given: 37 | def emailSender = Mock(EmailSender) { 38 | send(*_) >> { throw new RuntimeException(_reason) } 39 | } 40 | 41 | def userService = Mock(UserService) { 42 | getUserById(_) >> User.builder() 43 | .login(_login) 44 | .email("a@a.pl") 45 | .build() 46 | } 47 | 48 | and: 49 | def emailService = new EmailService(emailSender, userService) 50 | 51 | when: 52 | def send = emailService.asyncSend("login", _message).join() 53 | 54 | then: 55 | send == "FAIL: Sending email {$_message} to $_login reason: java.lang.RuntimeException: $_reason" 56 | 57 | where: 58 | _login | _message | _reason 59 | "login" | "message" | "reason" 60 | } 61 | 62 | def "send - without exception"() { 63 | given: 64 | def emailSender = new EmailSender() 65 | def userService = Mock(UserService) { 66 | getUserById(_) >> User.builder() 67 | .login(_login) 68 | .email("a@a.pl") 69 | .build() 70 | } 71 | 72 | and: 73 | def emailService = new EmailService(emailSender, userService) 74 | 75 | when: 76 | def send = emailService.send(_login, _message) 77 | 78 | then: 79 | send == "Email: {$_message} was sent to: $_login." 80 | 81 | where: 82 | _login | _message 83 | "login" | "message" 84 | } 85 | 86 | def "send - exception"() { 87 | given: 88 | def emailSender = Mock(EmailSender) { 89 | send(*_) >> { throw new RuntimeException(_reason) } 90 | } 91 | 92 | def userService = Mock(UserService) { 93 | getUserById(_) >> User.builder() 94 | .login(_login) 95 | .email("a@a.pl") 96 | .build() 97 | } 98 | 99 | and: 100 | def emailService = new EmailService(emailSender, userService) 101 | 102 | when: 103 | def send = emailService.send("login", _message) 104 | 105 | then: 106 | send == "FAIL: Sending email {$_message} to $_login reason: $_reason" 107 | 108 | where: 109 | _login | _message | _reason 110 | "login" | "message" | "reason" 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /email-service/src/test/java/com/example/emailservice/domain/user/service/UserServiceTest.groovy: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.domain.user.service 2 | 3 | import com.example.emailservice.domain.user.model.User 4 | import org.springframework.web.client.RestTemplate 5 | import spock.lang.Specification 6 | 7 | /** 8 | * Created by mtumilowicz on 2018-07-28. 9 | */ 10 | class UserServiceTest extends Specification { 11 | def "test getUserById"() { 12 | given: 13 | def user = User.builder() 14 | .login("login") 15 | .email("a@a.pl") 16 | .build() 17 | 18 | and: 19 | def restTemplate = Mock(RestTemplate) { 20 | getForObject({it.toString().contains('users/login')} as String, User.class) >> user 21 | } 22 | 23 | and: 24 | def service = new UserService(restTemplate) 25 | 26 | expect: 27 | service.getUserById("login") == user 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /email-service/src/test/java/com/example/emailservice/rest/controller/email/EmailControllerIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.rest.controller.email; 2 | 3 | import com.google.common.collect.ImmutableMap; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import static org.hamcrest.core.Is.is; 14 | import static org.junit.Assert.assertThat; 15 | 16 | /** 17 | * Created by mtumilowicz on 2018-07-28. 18 | */ 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 21 | public class EmailControllerIntegrationTest { 22 | 23 | @Autowired 24 | TestRestTemplate restTemplate; 25 | 26 | @LocalServerPort 27 | private int port; 28 | 29 | private static ImmutableMap request = ImmutableMap.of( 30 | "mtumilowicz", "4mtumilowicz", 31 | "hank", "4hank", 32 | "fjodor", "4fjodor", 33 | "ernie", "4ernie", 34 | "non-existing-user", "4non-existing-user" 35 | ); 36 | 37 | @Test 38 | public void asyncSend_status() { 39 | assertThat(restTemplate 40 | .postForEntity( 41 | createURLWithPort("emails/send/async"), 42 | request, 43 | Object[].class) 44 | .getStatusCode(), 45 | is(HttpStatus.OK)); 46 | } 47 | 48 | @Test 49 | public void send_status() { 50 | assertThat(restTemplate 51 | .postForEntity( 52 | createURLWithPort("emails/send"), 53 | request, 54 | Object[].class) 55 | .getStatusCode(), 56 | is(HttpStatus.OK)); 57 | } 58 | 59 | private String createURLWithPort(String uri) { 60 | return "http://localhost:" + port + uri; 61 | } 62 | } -------------------------------------------------------------------------------- /email-service/src/test/java/com/example/emailservice/rest/controller/email/EmailControllerTestHealthCheckTest.java: -------------------------------------------------------------------------------- 1 | package com.example.emailservice.rest.controller.email; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.boot.test.web.client.TestRestTemplate; 8 | import org.springframework.boot.web.server.LocalServerPort; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import static org.hamcrest.core.Is.is; 13 | import static org.junit.Assert.*; 14 | 15 | /** 16 | * Created by mtumilowicz on 2018-07-28. 17 | */ 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 20 | public class EmailControllerTestHealthCheckTest { 21 | 22 | @Autowired 23 | TestRestTemplate restTemplate; 24 | 25 | @LocalServerPort 26 | private int port; 27 | 28 | @Test 29 | public void health() { 30 | assertThat(restTemplate 31 | .getForEntity( 32 | createURLWithPort("emails/health"), 33 | null) 34 | .getStatusCode(), 35 | is(HttpStatus.OK)); 36 | } 37 | 38 | private String createURLWithPort(String uri) { 39 | return "http://localhost:" + port + uri; 40 | } 41 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | spring-boot-async 8 | spring-boot-async 9 | 1.0-SNAPSHOT 10 | pom 11 | 12 | 13 | email-service 14 | slow-user-service 15 | 16 | -------------------------------------------------------------------------------- /slow-user-service/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /slow-user-service/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mtumilowicz/spring-boot-async/2d44f7deb1e0fc9337698cc8ba36394b82424b41/slow-user-service/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /slow-user-service/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /slow-user-service/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /slow-user-service/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /slow-user-service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | slow-user-service 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | slow-user-service 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.projectlombok 35 | lombok 36 | true 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | com.google.guava 45 | guava 46 | 25.1-jre 47 | 48 | 49 | org.apache.commons 50 | commons-lang3 51 | 3.7 52 | 53 | 54 | org.spockframework 55 | spock-core 56 | 1.1-groovy-2.4 57 | test 58 | 59 | 60 | 61 | 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-maven-plugin 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/SlowUserServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SlowUserServiceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SlowUserServiceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/domain/user/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.domain.user.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | /** 7 | * Created by mtumilowicz on 2018-07-28. 8 | */ 9 | @Value 10 | @Builder 11 | public 12 | class User { 13 | String login; 14 | String firstName; 15 | String lastName; 16 | String email; 17 | } 18 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/domain/user/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.domain.user.service; 2 | 3 | import com.example.slowuserservice.infrastructure.exception.UserNotFoundException; 4 | import com.example.slowuserservice.infrastructure.repository.UserRepository; 5 | import com.example.slowuserservice.domain.user.model.User; 6 | import lombok.AccessLevel; 7 | import lombok.AllArgsConstructor; 8 | import lombok.experimental.FieldDefaults; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * Created by mtumilowicz on 2018-07-28. 13 | */ 14 | @Service 15 | @AllArgsConstructor 16 | @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) 17 | public class UserService { 18 | 19 | UserRepository repository; 20 | 21 | public User getById(String id) { 22 | return repository.getById(id).orElseThrow(() -> new UserNotFoundException(id)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/infrastructure/database/UsersDatabaseMock.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.infrastructure.database; 2 | 3 | import com.example.slowuserservice.domain.user.model.User; 4 | import com.google.common.collect.ImmutableMap; 5 | 6 | /** 7 | * Created by mtumilowicz on 2018-07-28. 8 | */ 9 | public class UsersDatabaseMock { 10 | public static final ImmutableMap users = ImmutableMap.of( 11 | "mtumilowicz", 12 | User.builder() 13 | .firstName("Michal") 14 | .lastName("Tumilowicz") 15 | .login("mtumilowicz") 16 | .email("mtumilowicz@gmail.com") 17 | .build(), 18 | "hank", 19 | User.builder() 20 | .firstName("Charles") 21 | .lastName("Bukowski") 22 | .login("hank") 23 | .email("hank@gmail.com") 24 | .build(), 25 | "fjodor", 26 | User.builder() 27 | .firstName("Fyodor") 28 | .lastName("Dostoevsky") 29 | .login("fjodor") 30 | .email("fjodor@gmail.com") 31 | .build(), 32 | "ernie", 33 | User.builder() 34 | .firstName("Ernest") 35 | .lastName("Hemingway") 36 | .login("ernie") 37 | .email("ErnestHemingway@gmail.com") 38 | .build() 39 | ); 40 | } 41 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/infrastructure/exception/UserNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.infrastructure.exception; 2 | 3 | /** 4 | * Created by mtumilowicz on 2018-07-28. 5 | */ 6 | public class UserNotFoundException extends RuntimeException { 7 | public UserNotFoundException(String id) { 8 | super("User not found - id = " + id); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/infrastructure/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.infrastructure.repository; 2 | 3 | import com.example.slowuserservice.infrastructure.database.UsersDatabaseMock; 4 | import com.example.slowuserservice.domain.user.model.User; 5 | import com.example.slowuserservice.infrastructure.utils.ThreadUtils; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.Optional; 10 | 11 | /** 12 | * Created by mtumilowicz on 2018-07-28. 13 | */ 14 | @Repository 15 | public class UserRepository { 16 | 17 | @Value("${user.repository.delay.seconds}") 18 | private Integer delay; 19 | 20 | public Optional getById(String id) { 21 | ThreadUtils.sleep(delay); 22 | return Optional.ofNullable(UsersDatabaseMock.users.get(id)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/infrastructure/utils/ThreadUtils.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.infrastructure.utils; 2 | 3 | /** 4 | * Created by mtumilowicz on 2018-07-28. 5 | */ 6 | public class ThreadUtils { 7 | public static void sleep(int seconds) { 8 | try { 9 | Thread.sleep(seconds * 1000); 10 | } catch (InterruptedException e) { 11 | // only for showcase purpose 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /slow-user-service/src/main/java/com/example/slowuserservice/rest/controller/user/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.rest.controller.user; 2 | 3 | import com.example.slowuserservice.domain.user.model.User; 4 | import com.example.slowuserservice.domain.user.service.UserService; 5 | import lombok.AccessLevel; 6 | import lombok.AllArgsConstructor; 7 | import lombok.experimental.FieldDefaults; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | /** 15 | * Created by mtumilowicz on 2018-07-28. 16 | */ 17 | @RestController 18 | @AllArgsConstructor 19 | @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) 20 | @RequestMapping("users") 21 | public class UserController { 22 | 23 | UserService service; 24 | 25 | @GetMapping("{login}") 26 | public ResponseEntity getById(@PathVariable("login") String login) { 27 | return ResponseEntity.ok(service.getById(login)); 28 | } 29 | 30 | @GetMapping("health") 31 | public void health() { 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /slow-user-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | user.repository.delay.seconds=1 2 | server.port = 8090 -------------------------------------------------------------------------------- /slow-user-service/src/test/java/com/example/slowuserservice/domain/user/service/UserServiceTest.groovy: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.domain.user.service 2 | 3 | import com.example.slowuserservice.domain.user.model.User 4 | import com.example.slowuserservice.infrastructure.exception.UserNotFoundException 5 | import com.example.slowuserservice.infrastructure.repository.UserRepository 6 | import spock.lang.Specification 7 | 8 | /** 9 | * Created by mtumilowicz on 2018-07-28. 10 | */ 11 | class UserServiceTest extends Specification { 12 | def "test getById - found"() { 13 | given: 14 | def user = User.builder().build() 15 | 16 | and: 17 | def userRepository = Mock(UserRepository) { 18 | getById("login") >> Optional.of(user) 19 | } 20 | 21 | and: 22 | def service = new UserService(userRepository) 23 | 24 | expect: 25 | service.getById("login") == user 26 | } 27 | 28 | def "test getById - not found"() { 29 | given: 30 | def userRepository = Mock(UserRepository) { 31 | getById("login") >> Optional.empty() 32 | } 33 | 34 | and: 35 | def service = new UserService(userRepository) 36 | 37 | when: 38 | service.getById("login") 39 | 40 | then: 41 | thrown(UserNotFoundException) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /slow-user-service/src/test/java/com/example/slowuserservice/rest/controller/user/UserControllerHealthCheckTest.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.rest.controller.user; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.boot.test.web.client.TestRestTemplate; 8 | import org.springframework.boot.web.server.LocalServerPort; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import static org.hamcrest.core.Is.is; 13 | import static org.junit.Assert.assertThat; 14 | 15 | /** 16 | * Created by mtumilowicz on 2018-07-28. 17 | */ 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 20 | public class UserControllerHealthCheckTest { 21 | @Autowired 22 | TestRestTemplate restTemplate; 23 | 24 | @LocalServerPort 25 | private int port; 26 | 27 | @Test 28 | public void health() { 29 | assertThat(restTemplate 30 | .getForEntity( 31 | createURLWithPort("users/health"), 32 | null) 33 | .getStatusCode(), 34 | is(HttpStatus.OK)); 35 | } 36 | 37 | private String createURLWithPort(String uri) { 38 | return "http://localhost:" + port + uri; 39 | } 40 | } -------------------------------------------------------------------------------- /slow-user-service/src/test/java/com/example/slowuserservice/rest/controller/user/UserControllerIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.rest.controller.user; 2 | 3 | import com.example.slowuserservice.domain.user.model.User; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import static org.hamcrest.core.Is.is; 14 | import static org.junit.Assert.assertThat; 15 | 16 | /** 17 | * Created by mtumilowicz on 2018-07-28. 18 | */ 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 21 | public class UserControllerIntegrationTest { 22 | @Autowired 23 | TestRestTemplate restTemplate; 24 | 25 | @LocalServerPort 26 | private int port; 27 | 28 | @Test 29 | public void getById_status_mtumilowicz() { 30 | assertThat(restTemplate 31 | .getForEntity( 32 | createURLWithPort("users/mtumilowicz"), 33 | null) 34 | .getStatusCode(), 35 | is(HttpStatus.OK)); 36 | } 37 | 38 | @Test 39 | public void getById_response_mtumilowicz() { 40 | assertThat(restTemplate 41 | .getForObject( 42 | createURLWithPort("users/mtumilowicz"), 43 | User.class), 44 | is(User.builder() 45 | .firstName("Michal") 46 | .lastName("Tumilowicz") 47 | .login("mtumilowicz") 48 | .email("mtumilowicz@gmail.com") 49 | .build())); 50 | } 51 | 52 | private String createURLWithPort(String uri) { 53 | return "http://localhost:" + port + uri; 54 | } 55 | } -------------------------------------------------------------------------------- /slow-user-service/src/test/java/com/example/slowuserservice/rest/controller/user/UserControllerTest.groovy: -------------------------------------------------------------------------------- 1 | package com.example.slowuserservice.rest.controller.user 2 | 3 | import com.example.slowuserservice.domain.user.service.UserService 4 | import spock.lang.Specification 5 | 6 | /** 7 | * Created by mtumilowicz on 2018-07-28. 8 | */ 9 | class UserControllerTest extends Specification { 10 | def "test getById"() { 11 | given: 12 | def userService = Mock(UserService) 13 | 14 | and: 15 | def controller = new UserController(userService) 16 | 17 | when: 18 | controller.getById("login") 19 | 20 | then: 21 | 1 * userService.getById("login") 22 | } 23 | } 24 | --------------------------------------------------------------------------------