├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── kr │ │ └── dataportal │ │ └── distributedlock │ │ ├── DistributedLockApplication.kt │ │ ├── configuration │ │ └── ApplicationConfiguration.kt │ │ ├── domain │ │ ├── Domain.kt │ │ └── article │ │ │ ├── entity │ │ │ └── Article.kt │ │ │ ├── repository │ │ │ └── ArticleRepository.kt │ │ │ └── service │ │ │ └── ArticleCommand.kt │ │ ├── infrastructure │ │ ├── lock │ │ │ ├── DistributedLock.kt │ │ │ ├── DistributedLockAspect.kt │ │ │ ├── DistributedLockException.kt │ │ │ ├── DistributedSynchronizer.kt │ │ │ └── RedisDistributedSynchronizer.kt │ │ └── redis │ │ │ ├── LettuceRedisService.kt │ │ │ └── RedisService.kt │ │ └── utils │ │ ├── jsonx.kt │ │ └── objectx.kt └── resources │ └── application.yml └── test └── kotlin └── kr └── dataportal └── distributedlock └── infrastructure └── DistributedLockAspectTest.kt /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Kotlin SpringBoot DistributedLock 2 | 3 | * Write/Update에 대한 동시성 처리 이슈를 어떻게 해결할 수 있을까? 4 | * DBMS 레벨에서 Lock을 관리할 수도 있지만 I/O 자체의 비용이 매우 큼. 이에 애플리케이션 레벨 Lock을 이용하게끔 구성 5 | * 예제의 LockSynchronizer 구현체는 Redis 이지만 변경 가능한 구조로 설계하였음 6 | * distributedLock Annotation 에 대한 Lock Aspect 구현 7 | * 실제 운용 시 http request time-out, 분산락 획득 실패 시 retry 등 고려 필요 8 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("org.springframework.boot") version "2.5.4" 3 | id("io.spring.dependency-management") version "1.0.11.RELEASE" 4 | kotlin("jvm") version "1.5.21" 5 | kotlin("plugin.spring") version "1.5.21" 6 | kotlin("kapt") version "1.5.21" 7 | } 8 | 9 | configurations { 10 | compileOnly { 11 | extendsFrom(configurations.annotationProcessor.get()) 12 | } 13 | } 14 | 15 | group = "kr.dataportal" 16 | version = "0.0.1-SNAPSHOT" 17 | java.sourceCompatibility = JavaVersion.VERSION_11 18 | 19 | repositories { 20 | mavenCentral() 21 | } 22 | 23 | dependencies { 24 | implementation("org.springframework.boot:spring-boot-starter-web") 25 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 26 | implementation("org.jetbrains.kotlin:kotlin-reflect") 27 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 28 | 29 | // Jackson 30 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 31 | implementation("com.fasterxml.jackson.module:jackson-module-afterburner") 32 | 33 | // Redis 34 | implementation("org.springframework.boot:spring-boot-starter-data-redis") 35 | implementation("org.apache.commons:commons-pool2:2.10.0") 36 | 37 | // JPA 38 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 39 | 40 | testImplementation("org.springframework.boot:spring-boot-starter-test") 41 | testImplementation("io.mockk:mockk:1.12.1") 42 | testImplementation("io.strikt:strikt-core:0.33.0") 43 | } 44 | 45 | tasks.withType { 46 | kotlinOptions { 47 | freeCompilerArgs = listOf("-Xjsr305=strict") 48 | jvmTarget = "11" 49 | } 50 | } 51 | 52 | tasks.withType { 53 | useJUnitPlatform() 54 | } 55 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heli-os/kotlin-springboot-distributed-lock/1614b5e89ff4cf3f30a35104022d37f2bad50ff0/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlin-springboot-distributed-lock" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/DistributedLockApplication.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 5 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration 6 | import org.springframework.boot.runApplication 7 | import org.springframework.web.bind.annotation.GetMapping 8 | import org.springframework.web.bind.annotation.RestController 9 | import java.time.ZoneOffset 10 | import java.util.* 11 | import javax.annotation.PostConstruct 12 | 13 | /** 14 | * @Author Heli 15 | */ 16 | @SpringBootApplication(exclude = [DataSourceAutoConfiguration::class, HibernateJpaAutoConfiguration::class]) 17 | class DistributedLockApplication { 18 | 19 | @PostConstruct 20 | fun initialize() { 21 | TimeZone.setDefault(TimeZone.getTimeZone(ZoneOffset.UTC)) 22 | } 23 | } 24 | 25 | fun main(args: Array) { 26 | runApplication(*args) 27 | } 28 | 29 | @RestController 30 | class HelloRestController { 31 | 32 | @GetMapping( 33 | value = ["/hello"] 34 | ) 35 | fun hello(): String = "Hello, distributed-lock-sample" 36 | } 37 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/configuration/ApplicationConfiguration.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.configuration 2 | 3 | import kr.dataportal.distributedlock.domain.Domain 4 | import org.springframework.context.annotation.ComponentScan 5 | import org.springframework.context.annotation.Configuration 6 | 7 | /** 8 | * @Author Heli 9 | */ 10 | @ComponentScan(basePackageClasses = [Domain::class]) 11 | @Configuration 12 | internal class ApplicationConfiguration 13 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/domain/Domain.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.domain 2 | 3 | interface Domain 4 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/domain/article/entity/Article.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.domain.article.entity 2 | 3 | import kr.dataportal.distributedlock.utils.lateInit 4 | import kr.dataportal.distributedlock.utils.notNull 5 | 6 | /** 7 | * @Author Heli 8 | */ 9 | class Article private constructor( 10 | var title: String, 11 | ) { 12 | var id: Long? = lateInit() 13 | 14 | val requiredId: Long get() = id.notNull { "id must not be null" } 15 | 16 | fun update(title: String) = this.apply { 17 | this.title = title 18 | } 19 | 20 | companion object { 21 | 22 | fun of(title: String): Article = Article( 23 | title = title 24 | ) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/domain/article/repository/ArticleRepository.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.domain.article.repository 2 | 3 | import kr.dataportal.distributedlock.domain.article.entity.Article 4 | import org.springframework.stereotype.Repository 5 | import java.util.concurrent.atomic.AtomicLong 6 | 7 | /** 8 | * @Author Heli 9 | */ 10 | @Repository 11 | class ArticleRepository { 12 | 13 | private val articles = hashMapOf() 14 | private val pk: AtomicLong = AtomicLong(1) 15 | 16 | fun save(article: Article): Article { 17 | return article.apply { 18 | this.id = pk.getAndAdd(1L) 19 | articles[this.requiredId] = this 20 | } 21 | } 22 | 23 | fun findByIdOrNull(id: Long): Article? { 24 | return articles[id] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/domain/article/service/ArticleCommand.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.domain.article.service 2 | 3 | import kr.dataportal.distributedlock.domain.article.entity.Article 4 | import kr.dataportal.distributedlock.domain.article.repository.ArticleRepository 5 | import kr.dataportal.distributedlock.infrastructure.lock.DistributedLock 6 | import kr.dataportal.distributedlock.utils.notNull 7 | import org.slf4j.Logger 8 | import org.slf4j.LoggerFactory 9 | import org.springframework.stereotype.Service 10 | 11 | /** 12 | * @Author Heli 13 | */ 14 | @Service 15 | class ArticleCommand( 16 | private val articleRepository: ArticleRepository 17 | ) { 18 | 19 | fun create(title: String): Article { 20 | 21 | val article = Article.of( 22 | title = title 23 | ) 24 | 25 | return articleRepository.save(article) 26 | } 27 | 28 | 29 | @DistributedLock( 30 | name = ARTICLE_UPDATE_LOCK_PREFIX, 31 | key = [ 32 | "#articleId" 33 | ] 34 | ) 35 | fun update( 36 | articleId: Long, 37 | title: String 38 | ): Article { 39 | 40 | val article = articleRepository.findByIdOrNull(articleId).notNull { "Article 조회 실패" } 41 | article.update(title) 42 | 43 | return articleRepository.save(article) 44 | } 45 | 46 | companion object { 47 | private val log: Logger = LoggerFactory.getLogger(ArticleCommand::class.java) 48 | private const val ARTICLE_UPDATE_LOCK_PREFIX = "article-update-lock" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/lock/DistributedLock.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.lock 2 | 3 | /** 4 | * @Author Heli 5 | */ 6 | @Target(AnnotationTarget.FUNCTION) 7 | annotation class DistributedLock( 8 | 9 | val name: String, 10 | 11 | val key: Array, 12 | 13 | val separator: String = ":" 14 | ) 15 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/lock/DistributedLockAspect.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.lock 2 | 3 | import org.aspectj.lang.JoinPoint 4 | import org.aspectj.lang.ProceedingJoinPoint 5 | import org.aspectj.lang.annotation.Around 6 | import org.aspectj.lang.annotation.Aspect 7 | import org.aspectj.lang.reflect.MethodSignature 8 | import org.springframework.expression.EvaluationContext 9 | import org.springframework.expression.ExpressionParser 10 | import org.springframework.expression.spel.standard.SpelExpressionParser 11 | import org.springframework.expression.spel.support.StandardEvaluationContext 12 | import org.springframework.stereotype.Component 13 | 14 | /** 15 | * @Author Heli 16 | */ 17 | @Component 18 | @Aspect 19 | class DistributedLockAspect( 20 | private val distributedSynchronizer: DistributedSynchronizer 21 | ) { 22 | 23 | @Around("@annotation(distributedLock)") 24 | fun round(joinPoint: ProceedingJoinPoint, distributedLock: DistributedLock): Any? { 25 | val lockKey = lockKey(joinPoint, distributedLock) 26 | return distributedSynchronizer.synchronize(lockKey) { 27 | joinPoint.proceed() 28 | } 29 | } 30 | 31 | private fun lockKey(joinPoint: ProceedingJoinPoint, distributedLock: DistributedLock): String { 32 | val evaluationContext = createEvaluationContext(joinPoint) 33 | return distributedLock.key.asSequence() 34 | .map { EXPRESSION_PARSER.parseExpression(it) } 35 | .map { requireNotNull(it.getValue(evaluationContext)) { "@DistributedLock 의 키가 null 입니다 name[${distributedLock.name}] keyExpression[${it.expressionString}]" } } 36 | .joinToString( 37 | separator = distributedLock.separator, 38 | prefix = "${distributedLock.name}${distributedLock.separator}" 39 | ) 40 | } 41 | 42 | private fun createEvaluationContext(joinPoint: ProceedingJoinPoint): EvaluationContext { 43 | val parameters = joinPoint.parameters 44 | return StandardEvaluationContext().apply { setVariables(parameters) } 45 | } 46 | 47 | private val JoinPoint.parameters 48 | get() = (signature as MethodSignature).parameterNames.asSequence().zip(args.asSequence()).toMap() 49 | 50 | companion object { 51 | private val EXPRESSION_PARSER: ExpressionParser = SpelExpressionParser() 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/lock/DistributedLockException.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.lock 2 | 3 | /** 4 | * @Author Heli 5 | */ 6 | class DistributedLockException(message: String) : RuntimeException(message) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/lock/DistributedSynchronizer.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.lock 2 | 3 | import java.util.concurrent.locks.Lock 4 | 5 | /** 6 | * @Author Heli 7 | */ 8 | interface DistributedSynchronizer { 9 | fun synchronize(key: String, synchronizedBlock: () -> T): T 10 | } 11 | 12 | internal abstract class AbstractDistributedSynchronizer : DistributedSynchronizer { 13 | 14 | abstract fun generateLock(key: String): Lock 15 | 16 | override fun synchronize(key: String, synchronizedBlock: () -> T): T { 17 | 18 | val lock = generateLock(key) 19 | 20 | if (!lock.tryLock()) { 21 | throw DistributedLockException("분산락 획득 실패 [$key]") 22 | } 23 | 24 | return try { 25 | synchronizedBlock() 26 | } finally { 27 | lock.unlock() 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/lock/RedisDistributedSynchronizer.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.lock 2 | 3 | import kr.dataportal.distributedlock.infrastructure.redis.RedisService 4 | import org.springframework.stereotype.Component 5 | import java.time.Duration 6 | import java.util.concurrent.TimeUnit 7 | import java.util.concurrent.locks.Condition 8 | import java.util.concurrent.locks.Lock 9 | 10 | /** 11 | * @Author Heli 12 | */ 13 | @Component 14 | internal class RedisDistributedSynchronizer( 15 | private val redisService: RedisService 16 | ) : AbstractDistributedSynchronizer() { 17 | override fun generateLock(key: String): Lock { 18 | return RedisLock(REDIS_LOCK_PREFIX + key) 19 | } 20 | 21 | inner class RedisLock(private val key: String) : Lock { 22 | 23 | override fun tryLock(): Boolean { 24 | return redisService.setIfAbsent(key, true, REDIS_LOCK_DURATION) 25 | } 26 | 27 | override fun unlock() { 28 | redisService.delete(key) 29 | } 30 | 31 | override fun tryLock(time: Long, unit: TimeUnit): Boolean { 32 | throw UnsupportedOperationException() 33 | } 34 | 35 | override fun lock() { 36 | throw UnsupportedOperationException() 37 | } 38 | 39 | override fun lockInterruptibly() { 40 | throw UnsupportedOperationException() 41 | } 42 | 43 | override fun newCondition(): Condition { 44 | throw UnsupportedOperationException() 45 | } 46 | } 47 | 48 | companion object { 49 | /** 50 | * 혹시나 락이 풀리지 않는 상황을 방지하기 위해 최대 1분만 락을 잡음. 51 | */ 52 | private val REDIS_LOCK_DURATION: Duration = Duration.ofMinutes(1) 53 | private const val REDIS_LOCK_PREFIX = "lock:" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/redis/LettuceRedisService.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.redis 2 | 3 | import kr.dataportal.distributedlock.utils.parseJson 4 | import kr.dataportal.distributedlock.utils.toJson 5 | import org.springframework.data.redis.core.StringRedisTemplate 6 | import org.springframework.stereotype.Component 7 | import java.time.Duration 8 | 9 | /** 10 | * @Author Heli 11 | */ 12 | @Component 13 | internal class LettuceRedisService( 14 | private val redisTemplate: StringRedisTemplate 15 | ) : RedisService { 16 | 17 | override fun getOrNull(key: String, type: Class): T? { 18 | return redisTemplate.opsForValue()[key.redisKey()]?.parseJson(type) 19 | } 20 | 21 | override fun setIfAbsent(key: String, value: Any, duration: Duration): Boolean { 22 | return requireNotNull(redisTemplate.opsForValue().setIfAbsent(key.redisKey(), value.toJson(), duration)) 23 | } 24 | 25 | override fun delete(key: String): Boolean { 26 | return redisTemplate.delete(key.redisKey()) 27 | } 28 | 29 | private fun String.redisKey(): String { 30 | return KEY_PREFIX + this 31 | } 32 | 33 | companion object { 34 | private const val KEY_PREFIX = "dataportal.kr_heli.os:" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/infrastructure/redis/RedisService.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure.redis 2 | 3 | import java.time.Duration 4 | 5 | /** 6 | * @Author Heli 7 | */ 8 | interface RedisService { 9 | 10 | fun getOrNull(key: String, type: Class): T? 11 | 12 | fun setIfAbsent(key: String, value: Any, duration: Duration): Boolean 13 | 14 | fun delete(key: String): Boolean 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/utils/jsonx.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.utils 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect 4 | import com.fasterxml.jackson.annotation.PropertyAccessor 5 | import com.fasterxml.jackson.databind.DeserializationFeature 6 | import com.fasterxml.jackson.databind.ObjectMapper 7 | import com.fasterxml.jackson.databind.SerializationFeature 8 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule 9 | import com.fasterxml.jackson.module.afterburner.AfterburnerModule 10 | import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 11 | 12 | /** 13 | * @Author Heli 14 | */ 15 | 16 | val GLOBAL_OBJECT_MAPPER: ObjectMapper = 17 | jacksonObjectMapper() 18 | .configure(DeserializationFeature.USE_LONG_FOR_INTS, true) 19 | .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 20 | .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) 21 | .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE) 22 | .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) 23 | .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) 24 | .registerModules(JavaTimeModule(), AfterburnerModule()) 25 | 26 | fun String.parseJson(type: Class): T = GLOBAL_OBJECT_MAPPER.readValue(this, type) 27 | fun Any.toJson(): String = GLOBAL_OBJECT_MAPPER.writeValueAsString(this) 28 | -------------------------------------------------------------------------------- /src/main/kotlin/kr/dataportal/distributedlock/utils/objectx.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.utils 2 | 3 | /** 4 | * @Author Heli 5 | */ 6 | 7 | @Suppress("UNCHECKED_CAST") 8 | fun lateInit(): T = null as T 9 | 10 | inline fun T?.notNull(lazyMessage: () -> Any): T = requireNotNull(this, lazyMessage) 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | redis: 3 | lettuce: 4 | pool: 5 | max-wait: 1000ms 6 | timeout: 1000ms 7 | host: localhost 8 | port: 6379 9 | -------------------------------------------------------------------------------- /src/test/kotlin/kr/dataportal/distributedlock/infrastructure/DistributedLockAspectTest.kt: -------------------------------------------------------------------------------- 1 | package kr.dataportal.distributedlock.infrastructure 2 | 3 | import io.mockk.Called 4 | import io.mockk.every 5 | import io.mockk.impl.annotations.MockK 6 | import io.mockk.junit5.MockKExtension 7 | import io.mockk.slot 8 | import io.mockk.verify 9 | import kr.dataportal.distributedlock.infrastructure.lock.DistributedLock 10 | import kr.dataportal.distributedlock.infrastructure.lock.DistributedLockAspect 11 | import kr.dataportal.distributedlock.infrastructure.lock.DistributedSynchronizer 12 | import org.junit.jupiter.api.BeforeEach 13 | import org.junit.jupiter.api.Test 14 | import org.junit.jupiter.api.assertThrows 15 | import org.junit.jupiter.api.extension.ExtendWith 16 | import org.springframework.aop.aspectj.annotation.AspectJProxyFactory 17 | import org.springframework.stereotype.Component 18 | import strikt.api.expectThat 19 | import strikt.assertions.isEqualTo 20 | import strikt.assertions.isNotNull 21 | import strikt.assertions.startsWith 22 | 23 | @ExtendWith(MockKExtension::class) 24 | internal class DistributedLockAspectTest { 25 | 26 | @MockK 27 | private lateinit var distributedSynchronizer: DistributedSynchronizer 28 | 29 | private lateinit var proxy: Target 30 | 31 | @BeforeEach 32 | fun beforeEach() { 33 | val synchronizedBlock = slot<() -> Any?>() 34 | every { 35 | distributedSynchronizer.synchronize(any(), capture(synchronizedBlock)) 36 | } answers { synchronizedBlock.captured() } 37 | 38 | val pojo = Target() 39 | val factory = AspectJProxyFactory(pojo) 40 | factory.addAspect(DistributedLockAspect(distributedSynchronizer)) 41 | proxy = factory.getProxy() 42 | } 43 | 44 | @Test 45 | fun `입력받은 파라미터로 LockKey 를 만들어서 동기화 시킨다`() { 46 | 47 | val result = proxy.withLock(320, "dataportal.kr_heli.os", ObjectKey(42), "with lock") 48 | 49 | expectThat(result) isEqualTo "with lock" 50 | verify { 51 | distributedSynchronizer.synchronize( 52 | withArg { expectThat(it) isEqualTo "test-lock:320:dataportal.kr_heli.os:42" }, 53 | any() 54 | ) 55 | } 56 | } 57 | 58 | @Test 59 | fun `null 로 키를 만들순 없음`() { 60 | 61 | val exception = assertThrows { 62 | proxy.withLock(320, null, ObjectKey(42), "with lock") 63 | } 64 | 65 | expectThat(exception) 66 | .get { message } 67 | .isNotNull() 68 | .startsWith("@DistributedLock 의 키가 null 입니다") 69 | } 70 | 71 | @Test 72 | fun `DistributedLock 애노테이션이 없으면 동기화 하지 않는다`() { 73 | val result = proxy.withoutLock(320, "dataportal.kr_heli.os", ObjectKey(42), "without lock") 74 | 75 | expectThat(result) isEqualTo "without lock" 76 | verify { distributedSynchronizer wasNot Called } 77 | } 78 | 79 | @Test 80 | fun `입력받은 separator 로 키를 만든다`() { 81 | val result = proxy.withLockSeparator(320, "dataportal.kr_heli.os", ObjectKey(42), "with lock") 82 | 83 | expectThat(result) isEqualTo "with lock" 84 | verify { 85 | distributedSynchronizer.synchronize( 86 | withArg { expectThat(it) isEqualTo "test-lock_320_dataportal.kr_heli.os_42" }, 87 | any() 88 | ) 89 | } 90 | } 91 | 92 | 93 | @Component 94 | class Target { 95 | 96 | @DistributedLock( 97 | name = "test-lock", 98 | key = ["#intKey", "#stringKey", "#objectKey.value"] 99 | ) 100 | fun withLock(intKey: Int?, stringKey: String?, objectKey: ObjectKey?, message: String): String { 101 | return message 102 | } 103 | 104 | @DistributedLock( 105 | name = "test-lock", 106 | key = ["#intKey", "#stringKey", "#objectKey.value"], 107 | separator = "_" 108 | ) 109 | fun withLockSeparator(intKey: Int?, stringKey: String?, objectKey: ObjectKey?, message: String): String { 110 | return message 111 | } 112 | 113 | fun withoutLock(intKey: Int?, stringKey: String?, objectKey: ObjectKey?, message: String): String { 114 | return message 115 | } 116 | } 117 | 118 | class ObjectKey( 119 | val value: Int 120 | ) 121 | } 122 | --------------------------------------------------------------------------------