├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── kotlin │ └── com │ │ └── ginsberg │ │ └── counter │ │ ├── App.kt │ │ ├── api │ │ ├── CounterHandler.kt │ │ └── Routes.kt │ │ ├── config │ │ └── Redis.kt │ │ ├── data │ │ ├── CounterRepository.kt │ │ └── RedisCounterRepository.kt │ │ ├── model │ │ └── Model.kt │ │ └── service │ │ └── EventBus.kt └── resources │ └── application.properties └── test └── kotlin └── com └── ginsberg └── counter ├── api └── CounterRoutesTest.kt └── repository └── InMemoryCounterRepository.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | out/ 18 | 19 | ### NetBeans ### 20 | nbproject/private/ 21 | build/ 22 | nbbuild/ 23 | dist/ 24 | nbdist/ 25 | .nb-gradle/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Todd Ginsberg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Reactive Spring Boot 2 with Kotlin 2 | 3 | [![license](https://img.shields.io/github/license/tginsberg/springboot2-reactive-kotlin.svg)]() 4 | 5 | 6 | This code supports a [blog post I wrote](https://todd.ginsberg.com/post/springboot2-reactive-kotlin/), and implements a simple counter using Spring Boot 2.0, Kotlin, and Redis. 7 | 8 | **Update 2020-05-27:** There is a [new version of this project](https://github.com/tginsberg/springboot-reactive-kotlin-coroutines) using Kotlin Coroutines and an [accompanying blog post](https://todd.ginsberg.com/post/springboot-reactive-kotlin-coroutines/)! 9 | 10 | ### Getting The Code 11 | 12 | ``` 13 | git clone https://github.com/tginsberg/springboot2-reactive-kotlin.git 14 | ``` 15 | 16 | ### Requirements 17 | 18 | 0. Gradle 4.0+ 19 | 1. Java 1.8 20 | 2. Redis installed and ready to use 21 | 3. A cursory understanding of reactive concepts and Spring Boot 22 | 23 | ### Running the server 24 | 25 | ``` 26 | gradlew bootRun 27 | ``` 28 | 29 | ### Endpoints 30 | 31 | | Purpose | Method | URL | Accept Header | 32 | |--------------------------|--------|---------------------|---------------------| 33 | | Current state of counter | GET | `/api/counter` | `application/json` | 34 | | Counter event stream | GET | `/api/counter` | `text/event-stream` | 35 | | Increment counter | PUT | `/api/counter/up` | `application/json` | 36 | | Decrement counter | PUT | `/api/counter/down` | `application/json` | 37 | 38 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | kotlinVersion = '1.2.20' 4 | springBootVersion = '2.0.0.RELEASE' 5 | } 6 | repositories { 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 11 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}") 12 | classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}") 13 | } 14 | } 15 | 16 | apply plugin: 'kotlin' 17 | apply plugin: 'kotlin-spring' 18 | apply plugin: 'eclipse' 19 | apply plugin: 'org.springframework.boot' 20 | apply plugin: 'io.spring.dependency-management' 21 | 22 | group = 'com.ginsberg' 23 | version = '0.0.1-SNAPSHOT' 24 | sourceCompatibility = 1.8 25 | compileKotlin { 26 | kotlinOptions.jvmTarget = "1.8" 27 | } 28 | compileTestKotlin { 29 | kotlinOptions.jvmTarget = "1.8" 30 | } 31 | 32 | repositories { 33 | mavenCentral() 34 | } 35 | 36 | 37 | dependencies { 38 | compile('org.springframework.boot:spring-boot-starter-data-redis-reactive') 39 | compile('org.springframework.boot:spring-boot-starter-webflux') 40 | compile("org.jetbrains.kotlin:kotlin-stdlib-jre8") 41 | compile("org.jetbrains.kotlin:kotlin-reflect") 42 | compile("com.fasterxml.jackson.module:jackson-module-kotlin") 43 | testCompile('org.springframework.boot:spring-boot-starter-test') 44 | testCompile('io.projectreactor:reactor-test') 45 | } 46 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tginsberg/springboot2-reactive-kotlin/fe92391d0cf1df8b5e104fa66145a79cf49ab6b4/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/App.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter 6 | 7 | import org.springframework.boot.SpringApplication 8 | import org.springframework.boot.autoconfigure.SpringBootApplication 9 | 10 | @SpringBootApplication 11 | class App 12 | 13 | fun main(args: Array) { 14 | SpringApplication.run(App::class.java, *args) 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/api/CounterHandler.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.api 6 | 7 | import com.ginsberg.counter.data.CounterRepository 8 | import com.ginsberg.counter.model.CounterDown 9 | import com.ginsberg.counter.model.CounterState 10 | import com.ginsberg.counter.model.CounterUp 11 | import com.ginsberg.counter.service.EventBus 12 | import org.springframework.stereotype.Component 13 | import org.springframework.web.reactive.function.server.ServerRequest 14 | import org.springframework.web.reactive.function.server.ServerResponse 15 | import org.springframework.web.reactive.function.server.body 16 | import org.springframework.web.reactive.function.server.bodyToServerSentEvents 17 | import reactor.core.publisher.Mono 18 | 19 | 20 | @Component 21 | class CounterHandler(private val eventBus: EventBus, 22 | private val counterRepository: CounterRepository) { 23 | 24 | fun get(serverRequest: ServerRequest): Mono = 25 | ServerResponse 26 | .ok() 27 | .body( 28 | counterRepository.get() 29 | .map { CounterState(it) } 30 | ) 31 | 32 | fun up(serverRequest: ServerRequest): Mono = 33 | ServerResponse 34 | .ok() 35 | .body( 36 | counterRepository.up() 37 | .map { CounterState(it) } 38 | .doOnNext { eventBus.publish(CounterUp(it.value)) } 39 | ) 40 | 41 | fun down(serverRequest: ServerRequest): Mono = 42 | ServerResponse 43 | .ok() 44 | .body( 45 | counterRepository.down() 46 | .map { CounterState(it) } 47 | .doOnNext { eventBus.publish(CounterDown(it.value)) } 48 | ) 49 | 50 | fun stream(serverRequest: ServerRequest): Mono = 51 | ServerResponse 52 | .ok() 53 | .bodyToServerSentEvents(eventBus.subscribe()) 54 | 55 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/api/Routes.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.api 6 | 7 | import org.springframework.context.annotation.Bean 8 | import org.springframework.context.annotation.Configuration 9 | import org.springframework.http.MediaType 10 | import org.springframework.web.reactive.function.server.router 11 | 12 | @Configuration 13 | class Routes(private val counterHandler: CounterHandler) { 14 | 15 | @Bean 16 | fun counterRouter() = router { 17 | "/api/counter".nest { 18 | accept(MediaType.APPLICATION_JSON).nest { 19 | GET("/", counterHandler::get) 20 | PUT("/up", counterHandler::up) 21 | PUT("/down", counterHandler::down) 22 | } 23 | accept(MediaType.TEXT_EVENT_STREAM).nest { 24 | GET("/", counterHandler::stream) 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/config/Redis.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.config 6 | 7 | import org.springframework.context.annotation.Bean 8 | import org.springframework.context.annotation.Configuration 9 | import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory 10 | import org.springframework.data.redis.core.ReactiveRedisTemplate 11 | import org.springframework.data.redis.serializer.RedisSerializationContext 12 | 13 | 14 | @Configuration 15 | class Redis { 16 | 17 | @Bean 18 | fun template(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate = 19 | ReactiveRedisTemplate(factory, RedisSerializationContext.string()) 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/data/CounterRepository.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.data 6 | 7 | import reactor.core.publisher.Mono 8 | 9 | 10 | interface CounterRepository { 11 | fun up(): Mono 12 | fun down(): Mono 13 | fun get(): Mono 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/data/RedisCounterRepository.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.data 6 | 7 | import org.springframework.beans.factory.annotation.Value 8 | import org.springframework.data.redis.core.ReactiveRedisTemplate 9 | import org.springframework.data.redis.serializer.StringRedisSerializer 10 | import org.springframework.stereotype.Repository 11 | import reactor.core.publisher.Mono 12 | import java.nio.ByteBuffer 13 | 14 | 15 | @Repository 16 | class RedisCounterRepository(private val redisTemplate: ReactiveRedisTemplate, 17 | @Value("\${redis.counter.key:THE_COUNTER}") keyName: String) : CounterRepository { 18 | 19 | private val key = ByteBuffer.wrap(StringRedisSerializer().serialize(keyName)) 20 | 21 | override fun up(): Mono = 22 | redisTemplate.createMono { it.numberCommands().incr(key) } 23 | 24 | override fun down(): Mono = 25 | redisTemplate.createMono { it.numberCommands().decr(key) } 26 | 27 | override fun get(): Mono = 28 | redisTemplate.createMono { it.numberCommands().incrBy(key, 0L) } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/model/Model.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.model 6 | 7 | import java.time.LocalDateTime 8 | 9 | data class CounterState(val value: Long, 10 | val asOf: LocalDateTime = LocalDateTime.now()) 11 | 12 | sealed class CounterEvent(val type: String, 13 | val at: LocalDateTime = LocalDateTime.now()) 14 | 15 | data class CounterUp(val value: Long) : CounterEvent("up") 16 | data class CounterDown(val value: Long) : CounterEvent("down") 17 | 18 | -------------------------------------------------------------------------------- /src/main/kotlin/com/ginsberg/counter/service/EventBus.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.service 6 | 7 | import com.ginsberg.counter.model.CounterEvent 8 | import org.slf4j.Logger 9 | import org.slf4j.LoggerFactory 10 | import org.springframework.beans.factory.annotation.Value 11 | import org.springframework.stereotype.Service 12 | import reactor.core.publisher.Flux 13 | import reactor.core.publisher.ReplayProcessor 14 | 15 | 16 | @Service 17 | class EventBus(@Value("\${events.replay.size:16}") replaySize: Int = 16) { 18 | 19 | private val eventProcessor: ReplayProcessor = ReplayProcessor.create(replaySize) 20 | 21 | init { 22 | log.info("Replay Size is $replaySize") 23 | } 24 | 25 | fun publish(event: CounterEvent) { 26 | log.info("Publishing event: {}", event) 27 | eventProcessor.onNext(event) 28 | log.info("Published to eventProcessor: {}", event) 29 | } 30 | 31 | fun subscribe(): Flux = 32 | Flux.merge(eventProcessor) 33 | .onBackpressureDrop() 34 | .doOnCancel { log.debug("Subscription cancelled") } 35 | .doOnError { log.warn("Error in EventBus", it) } 36 | .doOnSubscribe { log.debug("Subscription created") } 37 | 38 | companion object { 39 | private val log: Logger = LoggerFactory.getLogger(EventBus::class.java) 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 4 | # Copyright (c) 2017 by Todd Ginsberg 5 | # 6 | 7 | # Pretty-print JSON 8 | spring.jackson.serialization.indent_output=true 9 | 10 | # Counter/Redis 11 | redis.counter.key=THE_COUNTER 12 | -------------------------------------------------------------------------------- /src/test/kotlin/com/ginsberg/counter/api/CounterRoutesTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.api 6 | 7 | import com.ginsberg.counter.model.CounterState 8 | import com.jayway.jsonpath.JsonPath 9 | import org.assertj.core.api.Assertions.assertThat 10 | import org.junit.Before 11 | import org.junit.Test 12 | import org.junit.runner.RunWith 13 | import org.springframework.beans.factory.annotation.Autowired 14 | import org.springframework.boot.test.context.SpringBootTest 15 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment 16 | import org.springframework.http.MediaType 17 | import org.springframework.test.annotation.DirtiesContext 18 | import org.springframework.test.context.junit4.SpringRunner 19 | import org.springframework.test.web.reactive.server.WebTestClient 20 | import org.springframework.web.reactive.function.server.RouterFunction 21 | import org.springframework.web.reactive.function.server.ServerResponse 22 | import reactor.test.StepVerifier 23 | import java.time.LocalDateTime 24 | 25 | 26 | @RunWith(SpringRunner::class) 27 | @SpringBootTest( 28 | webEnvironment = WebEnvironment.RANDOM_PORT 29 | ) 30 | class CounterRoutesTest { 31 | 32 | lateinit var webClient: WebTestClient 33 | 34 | @Autowired 35 | lateinit var route: RouterFunction 36 | 37 | lateinit var state: CounterState 38 | 39 | @Before 40 | fun before() { 41 | webClient = WebTestClient.bindToRouterFunction(route).build() 42 | 43 | state = webClient.get() 44 | .uri("/api/counter") 45 | .exchange() 46 | .expectStatus().isOk 47 | .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) 48 | .expectBody(CounterState::class.java) 49 | .returnResult().responseBody!! 50 | } 51 | 52 | @Test 53 | fun `get current value`() { 54 | assertThat(state.value).isNotNull() 55 | assertThat(state.asOf) 56 | .isNotNull() 57 | .isAfterOrEqualTo(LocalDateTime.now().minusSeconds(1)) 58 | .isBeforeOrEqualTo(LocalDateTime.now()) 59 | } 60 | 61 | @Test 62 | fun `increment counter`() { 63 | val event: String? = webClient.put() 64 | .uri("/api/counter/up") 65 | .exchange() 66 | .expectStatus().isOk 67 | .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) 68 | .expectBody(String::class.java) 69 | .returnResult() 70 | .responseBody 71 | 72 | assertThat(event).isNotNull() 73 | assertThat(JsonPath.read(event, "$.value", null)).isEqualTo(state.value.inc()) 74 | } 75 | 76 | @Test 77 | fun `decrement counter`() { 78 | val event: String? = webClient.put() 79 | .uri("/api/counter/down") 80 | .exchange() 81 | .expectStatus().isOk 82 | .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) 83 | .expectBody(String::class.java) 84 | .returnResult() 85 | .responseBody 86 | 87 | assertThat(event).isNotNull() 88 | assertThat(JsonPath.read(event, "$.value", null)).isEqualTo(state.value.dec()) 89 | 90 | } 91 | 92 | @Test 93 | @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) // Because of ReplayProcessor state. 94 | fun `stream receives events`() { 95 | 96 | // Send in an event, so the stream has something to emit or the next part 97 | // has trouble when using WebTestClient with this test in isolation for some reason. 98 | webClient.put().uri("/api/counter/up").exchange() 99 | 100 | val events = webClient.get() 101 | .uri("/api/counter") 102 | .accept(MediaType.TEXT_EVENT_STREAM) 103 | .exchange() 104 | .expectStatus().isOk 105 | .expectHeader().contentType(MediaType.TEXT_EVENT_STREAM) 106 | .returnResult(String::class.java) 107 | .responseBody 108 | 109 | StepVerifier.create(events) 110 | .assertNext { 111 | assertThat(JsonPath.read(it, "$.type", null)).isEqualToIgnoringCase("up") 112 | assertThat(JsonPath.read(it, "$.value", null)).isEqualTo(1L) 113 | } 114 | .then { 115 | webClient.put().uri("/api/counter/up").exchange() 116 | } 117 | .assertNext { 118 | assertThat(JsonPath.read(it, "$.type", null)).isEqualToIgnoringCase("up") 119 | assertThat(JsonPath.read(it, "$.value", null)).isEqualTo(2L) 120 | } 121 | .then { 122 | webClient.put().uri("/api/counter/down").exchange() 123 | } 124 | .assertNext { 125 | assertThat(JsonPath.read(it, "$.type", null)).isEqualToIgnoringCase("down") 126 | assertThat(JsonPath.read(it, "$.value", null)).isEqualTo(1L) 127 | } 128 | .thenCancel() 129 | .verify() 130 | } 131 | 132 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/ginsberg/counter/repository/InMemoryCounterRepository.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 by Todd Ginsberg 3 | */ 4 | 5 | package com.ginsberg.counter.repository 6 | 7 | import com.ginsberg.counter.data.CounterRepository 8 | import org.springframework.context.annotation.Primary 9 | import org.springframework.stereotype.Component 10 | import reactor.core.publisher.Mono 11 | import java.util.concurrent.atomic.AtomicLong 12 | 13 | /** 14 | * A version of CounterRepository to be used for testing. 15 | */ 16 | @Component 17 | @Primary // Will only be applied when in test mode. 18 | class InMemoryCounterRepository : CounterRepository { 19 | private val counter = AtomicLong(0L) 20 | 21 | override fun up(): Mono = 22 | Mono.just(counter.incrementAndGet()) 23 | 24 | override fun down(): Mono = 25 | Mono.just(counter.decrementAndGet()) 26 | 27 | override fun get(): Mono = 28 | Mono.just(counter.get()) 29 | 30 | } 31 | --------------------------------------------------------------------------------