├── .gitignore ├── Dockerfile ├── LICENSE.txt ├── README.md ├── build.gradle ├── docs └── performance-diagram.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── kotlin │ └── me │ │ └── ruslanys │ │ ├── Application.kt │ │ ├── annotation │ │ └── RequestMapping.kt │ │ ├── config │ │ └── ExecutorsConfig.kt │ │ ├── controller │ │ └── UserController.kt │ │ ├── domain │ │ └── UserDto.kt │ │ └── web │ │ ├── HttpChannelInitializer.kt │ │ ├── HttpControllerHandler.kt │ │ ├── HttpServer.kt │ │ └── PathHandlerProvider.kt └── resources │ └── application.properties └── test ├── kotlin └── me │ └── ruslanys │ └── config │ └── Mockito.kt └── resources └── application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | build/ 3 | *.iml -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8-jre-alpine 2 | 3 | WORKDIR root/ 4 | 5 | ADD build/libs/spring-boot-*.jar ./application.jar 6 | 7 | EXPOSE 8080 8 | 9 | CMD java -server -Xmx750M -jar /root/application.jar -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Ruslan Molchanov 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 | # Spring Boot + Netty 2 | 3 | # Description 4 | 5 | The repository is a **high**-performance tech stack based on [Spring Boot](https://projects.spring.io/spring-boot/) 6 | that using [Netty](https://netty.io/) instead of Spring Web MVC / Spring Webflux. 7 | 8 | 9 | ## Performance Comparison 10 | 11 | ### Environment 12 | 13 | KVM, Ubuntu 16.04, 2048 MB RAM, 2 CPU 14 | 15 | Run: `$ java -Xmx1024M -server -jar application.jar` 16 | 17 | Test: `$ wrk -t12 -c400 -d30s --latency http://host/api/user/current` 18 | 19 | ### Tomcat 20 | 21 | ``` 22 | Running 30s test @ http://host/api/user/current 23 | 12 threads and 400 connections 24 | Thread Stats Avg Stdev Max +/- Stdev 25 | Latency 54.66ms 64.39ms 996.17ms 92.02% 26 | Req/Sec 744.51 140.25 3.08k 85.77% 27 | Latency Distribution 28 | 50% 42.26ms 29 | 75% 65.72ms 30 | 90% 105.89ms 31 | 99% 275.51ms 32 | 265240 requests in 30.06s, 53.93MB read 33 | Requests/sec: 8822.80 34 | Transfer/sec: 1.79MB 35 | ``` 36 | 37 | 38 | ### Undertow 39 | 40 | ``` 41 | Running 30s test @ http://host/api/user/current 42 | 12 threads and 400 connections 43 | Thread Stats Avg Stdev Max +/- Stdev 44 | Latency 66.80ms 121.30ms 1.94s 91.37% 45 | Req/Sec 0.87k 327.28 6.07k 91.60% 46 | Latency Distribution 47 | 50% 27.18ms 48 | 75% 77.43ms 49 | 90% 172.98ms 50 | 99% 505.67ms 51 | 303177 requests in 30.04s, 51.47MB read 52 | Socket errors: connect 0, read 0, write 0, timeout 148 53 | Requests/sec: 10090.98 54 | Transfer/sec: 1.71MB 55 | ``` 56 | 57 | ### Spring Reactive - Webflux 58 | 59 | ``` 60 | Running 30s test @ http://host/api/user/current 61 | 12 threads and 400 connections 62 | Thread Stats Avg Stdev Max +/- Stdev 63 | Latency 64.22ms 101.43ms 2.00s 89.74% 64 | Req/Sec 0.88k 332.80 7.93k 93.13% 65 | Latency Distribution 66 | 50% 27.41ms 67 | 75% 77.47ms 68 | 90% 168.43ms 69 | 99% 432.62ms 70 | 306800 requests in 30.10s, 52.08MB read 71 | Socket errors: connect 0, read 0, write 0, timeout 36 72 | Requests/sec: 10193.27 73 | Transfer/sec: 1.73MB 74 | ``` 75 | 76 | 77 | ### This 78 | 79 | ``` 80 | Running 30s test @ http://host/api/user/current 81 | 12 threads and 400 connections 82 | Thread Stats Avg Stdev Max +/- Stdev 83 | Latency 25.38ms 41.24ms 460.39ms 90.51% 84 | Req/Sec 2.38k 325.27 4.46k 88.33% 85 | Latency Distribution 86 | 50% 12.09ms 87 | 75% 18.72ms 88 | 90% 63.93ms 89 | 99% 215.51ms 90 | 845952 requests in 30.05s, 129.08MB read 91 | Requests/sec: 28151.60 92 | Transfer/sec: 4.30MB 93 | ``` 94 | 95 | ### Overview 96 | 97 | ![Diagram](docs/performance-diagram.png) 98 | 99 | So, this stack in 2.8 times faster than Undertow and Webflux and in 3.18 times faster than Tomcat. 100 | 101 | The difference in rates becomes higher with more performance hardware. -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.jetbrains.kotlin.jvm' version '1.2.21' 3 | id 'org.jetbrains.kotlin.plugin.spring' version '1.2.21' 4 | id 'org.jetbrains.kotlin.plugin.jpa' version '1.2.21' 5 | id 'org.springframework.boot' version '1.5.10.RELEASE' 6 | } 7 | 8 | 9 | group = 'me.ruslanys' 10 | version = '0.1' 11 | sourceCompatibility = JavaVersion.VERSION_1_8 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | ext.kotlinVersion = '1.2.21' 18 | ext.nettyVersion = '4.1.21.Final' 19 | 20 | dependencies { 21 | compile('org.springframework.boot:spring-boot-starter') 22 | compile("io.netty:netty-all:${nettyVersion}") 23 | 24 | // Kotlin 25 | compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}") 26 | compile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") 27 | compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.9.4.1") 28 | 29 | // DevTools 30 | compileOnly('org.springframework.boot:spring-boot-configuration-processor') 31 | 32 | // Tests 33 | testCompile('org.springframework.boot:spring-boot-starter-test') 34 | } 35 | 36 | // Jar 37 | jar { 38 | manifest { 39 | attributes("Implementation-Version": version) 40 | } 41 | } 42 | 43 | // Kotlin 44 | compileKotlin { 45 | kotlinOptions { 46 | jvmTarget = "1.8" 47 | } 48 | } 49 | compileTestKotlin { 50 | kotlinOptions { 51 | jvmTarget = "1.8" 52 | } 53 | } 54 | sourceSets { 55 | main.kotlin.srcDirs += 'src/main/kotlin' 56 | } 57 | noArg { 58 | annotations("javax.persistence.MappedSuperclass", "javax.persistence.Entity") 59 | } -------------------------------------------------------------------------------- /docs/performance-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruslanys/sample-spring-boot-netty/add9fe65cbe85c7c421ff51a209a1156d35c01a9/docs/performance-diagram.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruslanys/sample-spring-boot-netty/add9fe65cbe85c7c421ff51a209a1156d35c01a9/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.5.1-all.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 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name='spring-boot-netty' -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/Application.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys 2 | 3 | import org.springframework.boot.SpringApplication 4 | import org.springframework.boot.autoconfigure.SpringBootApplication 5 | 6 | @SpringBootApplication 7 | class Application 8 | 9 | fun main(args: Array) { 10 | SpringApplication.run(Application::class.java, *args) 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/annotation/RequestMapping.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.annotation 2 | 3 | @Retention(AnnotationRetention.RUNTIME) 4 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) 5 | annotation class RequestMapping( 6 | val value: String 7 | ) 8 | -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/config/ExecutorsConfig.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.config 2 | 3 | import org.slf4j.LoggerFactory 4 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler 5 | import org.springframework.context.annotation.Configuration 6 | import org.springframework.scheduling.annotation.AsyncConfigurer 7 | import org.springframework.scheduling.annotation.EnableAsync 8 | import org.springframework.scheduling.annotation.EnableScheduling 9 | import org.springframework.scheduling.annotation.SchedulingConfigurer 10 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor 11 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler 12 | import org.springframework.scheduling.config.ScheduledTaskRegistrar 13 | import java.util.concurrent.Executor 14 | 15 | 16 | @Configuration 17 | @EnableScheduling 18 | @EnableAsync 19 | class ExecutorsConfig : SchedulingConfigurer, AsyncConfigurer { 20 | 21 | companion object { 22 | private const val SCHEDULER_POOL_SIZE = 5 23 | private const val ASYNC_POOL_SIZE = 10 24 | } 25 | 26 | override fun configureTasks(taskRegistrar: ScheduledTaskRegistrar) { 27 | val taskScheduler = ThreadPoolTaskScheduler() 28 | taskScheduler.poolSize = SCHEDULER_POOL_SIZE 29 | taskScheduler.initialize() 30 | taskScheduler.threadNamePrefix = "ScheduledExecutor-" 31 | 32 | taskRegistrar.setTaskScheduler(taskScheduler) 33 | } 34 | 35 | override fun getAsyncUncaughtExceptionHandler(): AsyncUncaughtExceptionHandler = 36 | AsyncUncaughtExceptionHandler { throwable, _, _ -> 37 | LoggerFactory.getLogger("Async").error("Async error", throwable) 38 | } 39 | 40 | override fun getAsyncExecutor(): Executor { 41 | val executor = ThreadPoolTaskExecutor() 42 | executor.corePoolSize = ASYNC_POOL_SIZE 43 | executor.threadNamePrefix = "AsyncExecutor-" 44 | executor.initialize() 45 | return executor 46 | } 47 | 48 | 49 | } -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/controller/UserController.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.controller 2 | 3 | import io.netty.handler.codec.http.FullHttpRequest 4 | import me.ruslanys.annotation.RequestMapping 5 | import me.ruslanys.domain.UserDto 6 | import org.springframework.stereotype.Controller 7 | 8 | @Controller 9 | class UserController { 10 | 11 | @RequestMapping("/api/user/current") 12 | fun getCurrentUser(request: FullHttpRequest): Any? { 13 | return UserDto("Ruslan", "Molchanov", "ruslanys@gmail.com") 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/domain/UserDto.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.domain 2 | 3 | import org.springframework.util.DigestUtils 4 | 5 | class UserDto(firstName: String, lastName: String, email: String) { 6 | 7 | val name: String = "$firstName $lastName" 8 | val emailHash: String = DigestUtils.md5DigestAsHex(email.toByteArray()) 9 | 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/web/HttpChannelInitializer.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.web 2 | 3 | import io.netty.channel.ChannelInitializer 4 | import io.netty.channel.socket.SocketChannel 5 | import io.netty.handler.codec.http.HttpObjectAggregator 6 | import io.netty.handler.codec.http.HttpRequestDecoder 7 | import io.netty.handler.codec.http.HttpResponseEncoder 8 | import org.springframework.stereotype.Component 9 | 10 | @Component 11 | class HttpChannelInitializer(val httpControllerHandler: HttpControllerHandler) : ChannelInitializer() { 12 | 13 | override fun initChannel(ch: SocketChannel) { 14 | val pipeline = ch.pipeline() 15 | pipeline.addLast(HttpRequestDecoder()) 16 | pipeline.addLast(HttpObjectAggregator(1048576)) 17 | pipeline.addLast(HttpResponseEncoder()) 18 | pipeline.addLast(httpControllerHandler) 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/web/HttpControllerHandler.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.web 2 | 3 | import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 4 | import io.netty.buffer.Unpooled.wrappedBuffer 5 | import io.netty.channel.ChannelHandler 6 | import io.netty.channel.ChannelHandlerContext 7 | import io.netty.channel.SimpleChannelInboundHandler 8 | import io.netty.handler.codec.http.* 9 | import io.netty.handler.codec.http.HttpHeaderValues.APPLICATION_JSON 10 | import io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN 11 | import io.netty.util.AsciiString 12 | import org.slf4j.LoggerFactory 13 | import org.springframework.stereotype.Component 14 | 15 | @ChannelHandler.Sharable 16 | @Component 17 | class HttpControllerHandler(private val pathHandlerProvider: PathHandlerProvider) : SimpleChannelInboundHandler() { 18 | 19 | companion object { 20 | private val log = LoggerFactory.getLogger(this::class.java) 21 | private val jacksonObjectMapper = jacksonObjectMapper() 22 | } 23 | 24 | override fun channelRead0(ctx: ChannelHandlerContext, request: FullHttpRequest) { 25 | var responseStatus = HttpResponseStatus.OK 26 | var responseBody = "" 27 | var mimeType = APPLICATION_JSON 28 | 29 | try { 30 | val handler = pathHandlerProvider.getHandler(request) 31 | if (handler == null) { 32 | writeResponse(ctx, HttpResponseStatus.NOT_FOUND, TEXT_PLAIN, "Not found.") 33 | return 34 | } 35 | 36 | val response = handler(request) 37 | 38 | if (response is String) { 39 | responseBody = response 40 | } else if (response != null) { 41 | responseBody = toJson(response) 42 | } 43 | } catch (e: Exception) { 44 | responseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR 45 | responseBody = e.message ?: "" 46 | mimeType = TEXT_PLAIN 47 | } 48 | 49 | writeResponse(ctx, responseStatus, mimeType, responseBody) 50 | } 51 | 52 | private fun toJson(any: Any): String { 53 | return jacksonObjectMapper.writeValueAsString(any) 54 | } 55 | 56 | private fun writeResponse(ctx: ChannelHandlerContext, status: HttpResponseStatus, mimeType: AsciiString, body: String) { 57 | val buf = wrappedBuffer(body.toByteArray()) 58 | val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buf) 59 | 60 | response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()) 61 | response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeType.toString() + "; charset=UTF-8") 62 | HttpUtil.setKeepAlive(response, true) 63 | 64 | ctx.writeAndFlush(response) 65 | } 66 | 67 | @Throws(Exception::class) 68 | override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) { 69 | log.error("Something went wrong", cause) 70 | writeResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, TEXT_PLAIN, cause.message ?: "") 71 | } 72 | 73 | 74 | 75 | } -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/web/HttpServer.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.web 2 | 3 | import io.netty.bootstrap.ServerBootstrap 4 | import io.netty.channel.ChannelOption 5 | import io.netty.channel.epoll.EpollEventLoopGroup 6 | import io.netty.channel.epoll.EpollServerSocketChannel 7 | import org.slf4j.LoggerFactory 8 | import org.springframework.beans.factory.annotation.Value 9 | import org.springframework.boot.CommandLineRunner 10 | import org.springframework.stereotype.Component 11 | import java.util.* 12 | import javax.annotation.PreDestroy 13 | 14 | 15 | @Component 16 | class HttpServer(@Value("\${server.port:8080}") port: Int, 17 | private val httpChannelInitializer: HttpChannelInitializer) : CommandLineRunner { 18 | 19 | companion object { 20 | private val log = LoggerFactory.getLogger(HttpServer::class.java) 21 | } 22 | 23 | private val bossGroup = EpollEventLoopGroup(1) 24 | private val workerGroup = EpollEventLoopGroup() // 12? 25 | private val port: Int 26 | 27 | init { 28 | if (port == -1) { 29 | this.port = 1024 + Random().nextInt(48_128) 30 | } else { 31 | this.port = port 32 | } 33 | } 34 | 35 | 36 | override fun run(vararg args: String?) { 37 | try { 38 | val sb = ServerBootstrap() 39 | .group(bossGroup, workerGroup) 40 | .channel(EpollServerSocketChannel::class.java) 41 | .childHandler(httpChannelInitializer) 42 | .option(ChannelOption.SO_BACKLOG, 512) 43 | .childOption(ChannelOption.SO_KEEPALIVE, true) 44 | .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) 45 | 46 | val future = sb.bind(port) 47 | log.info("Server is started on {} port.", port) 48 | 49 | future.sync() // locking the thread until groups are going on 50 | future.channel().closeFuture().sync() 51 | } catch (e: InterruptedException) { 52 | log.error("Something went wrong", e) 53 | } finally { 54 | shutdown() 55 | } 56 | } 57 | 58 | @PreDestroy 59 | fun shutdown() { 60 | log.info("Server is shutting down.") 61 | bossGroup.shutdownGracefully() 62 | workerGroup.shutdownGracefully() 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/kotlin/me/ruslanys/web/PathHandlerProvider.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.web 2 | 3 | import io.netty.handler.codec.http.FullHttpRequest 4 | import me.ruslanys.annotation.RequestMapping 5 | import org.springframework.context.ApplicationContext 6 | import org.springframework.stereotype.Component 7 | import org.springframework.stereotype.Controller 8 | import java.util.* 9 | import javax.annotation.PostConstruct 10 | import kotlin.reflect.full.* 11 | import kotlin.reflect.jvm.javaMethod 12 | 13 | @Component 14 | class PathHandlerProvider(private val context: ApplicationContext) { 15 | 16 | private val storage = TreeMap>() 17 | 18 | @PostConstruct 19 | private fun init() { 20 | val beans = context.getBeansWithAnnotation(Controller::class.java).values 21 | for (bean in beans) { 22 | val functions = bean::class.declaredFunctions 23 | 24 | for (function in functions) { 25 | val pathAnnotation = function.findAnnotation() ?: continue 26 | val path = pathAnnotation.value 27 | 28 | val parameters = function.valueParameters 29 | val parameter = parameters.first() 30 | if (parameters.size > 1 || !parameter.type.isSubtypeOf(FullHttpRequest::class.createType())) { 31 | throw IllegalStateException("Incorrect parameter type of " + 32 | "${function.javaMethod!!.declaringClass.name}.${function.name}") 33 | } 34 | 35 | if (storage.containsKey(pathAnnotation.value)) { 36 | throw IllegalStateException("Mapping $path is already exists.") 37 | } else { 38 | storage[path] = { request -> 39 | function.call(bean, request) 40 | } 41 | } 42 | } 43 | } 44 | } 45 | 46 | fun getHandler(request: FullHttpRequest) : ((FullHttpRequest) -> Any?)? { 47 | for (entry in storage) { 48 | if (request.uri().startsWith(entry.key)) { 49 | return entry.value 50 | } 51 | } 52 | 53 | return null 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | -------------------------------------------------------------------------------- /src/test/kotlin/me/ruslanys/config/Mockito.kt: -------------------------------------------------------------------------------- 1 | package me.ruslanys.config 2 | 3 | import org.mockito.Mockito 4 | 5 | fun any(clazz: Class): T = Mockito.any(clazz) -------------------------------------------------------------------------------- /src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | --------------------------------------------------------------------------------