├── .gitignore ├── README.md ├── build.gradle.kts ├── example ├── .gitignore ├── build.gradle.kts ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src │ ├── main │ ├── kotlin │ │ └── com │ │ │ └── dteknoloji │ │ │ └── reactivecacheexample │ │ │ ├── ReactiveCacheExampleApplication.kt │ │ │ ├── Todo.kt │ │ │ ├── TodoApiClient.kt │ │ │ ├── TodoController.kt │ │ │ └── TodoService.kt │ └── resources │ │ └── application.yml │ └── test │ └── kotlin │ └── com │ └── dteknoloji │ └── reactivecacheexample │ └── ReactiveCacheExampleApplicationTests.kt ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── com │ │ └── dteknoloji │ │ └── springredisreactivecache │ │ ├── annotation │ │ ├── EnableReactiveCaching.kt │ │ ├── RedisReactiveCacheEvict.kt │ │ ├── RedisReactiveCacheGet.kt │ │ └── RedisReactiveCachePut.kt │ │ ├── aspect │ │ └── ReactiveRedisCacheAspect.kt │ │ ├── config │ │ └── ReactiveCachingConfiguration.kt │ │ └── util │ │ ├── Extensions.kt │ │ └── ReactiveCacheUtils.kt └── resources │ └── application.properties └── test ├── kotlin └── com │ └── dteknoloji │ └── springredisreactivecache │ ├── TestUtils.kt │ ├── aspect │ └── ReactiveRedisCacheAspectTest.kt │ ├── dto │ ├── CacheableCustomer.kt │ └── DummyGetRequest.kt │ ├── integration │ └── IntegrationTest.kt │ ├── service │ └── CustomerTestService.kt │ └── util │ └── ReactiveCacheUtilsTest.kt └── resources └── application.yml /.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 | ## spring-redis-reactive-cache 2 | Adds annotation support to Spring for reactive cache operations 3 | 4 | >Note : Works only with Kotlin. 5 | 6 | ### Usage 7 | 8 | First add Jitpack to repositories: 9 | >`maven { url 'https://jitpack.io' }` 10 | 11 | Add dependency: 12 | >`implementation("com.github.DogusTeknoloji:spring-redis-reactive-cache:1.0.3")` 13 | 14 | ```kotlin 15 | @Service 16 | class TodoService(private val todoApiClient: WebClient) { 17 | 18 | @RedisReactiveCacheGet(key = "#id", keyPrefix = "TODO_", hashKey = "TODOS") 19 | suspend fun getById(id: Int, cacheFirst: Boolean = false): Todo { 20 | return todoApiClient.get() 21 | .uri { 22 | it.path("/{id}").build(id) 23 | } 24 | .retrieve() 25 | .awaitBody() 26 | } 27 | 28 | @RedisReactiveCachePut(keyPrefix = "TODO_", hashKey = "TODOS", expireDuration = "P1D") 29 | suspend fun create(todo: Todo): Todo { 30 | return todoApiClient.post() 31 | .bodyValue(todo) 32 | .retrieve() 33 | .awaitBody() 34 | } 35 | 36 | @RedisReactiveCacheEvict(keyPrefix = "TODO_", key = "#id", hashKey = "TODOS") 37 | suspend fun delete(id: Int) { 38 | todoApiClient.delete() 39 | .uri { 40 | it.path("/{id}").build(id) 41 | } 42 | .retrieve() 43 | .awaitBodilessEntity() 44 | } 45 | } 46 | ``` 47 | 48 | [Full example](https://github.com/DogusTeknoloji/spring-redis-reactive-cache/tree/main/example) 49 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.7.3" 5 | id("io.spring.dependency-management") version "1.0.13.RELEASE" 6 | id("org.jlleitschuh.gradle.ktlint") version "11.0.0" 7 | `maven-publish` 8 | kotlin("jvm") version "1.6.21" 9 | kotlin("plugin.spring") version "1.6.21" 10 | } 11 | 12 | group = "com.dteknoloji" 13 | version = "1.0.3" 14 | java.sourceCompatibility = JavaVersion.VERSION_17 15 | 16 | repositories { 17 | mavenCentral() 18 | maven { url = uri("https://jitpack.io") } 19 | } 20 | 21 | publishing { 22 | publications { 23 | create("maven") { 24 | groupId = "com.dteknoloji" 25 | version = "1.0.3" 26 | artifactId = "spring-redis-reactive-cache" 27 | from(components["java"]) 28 | } 29 | } 30 | } 31 | 32 | extra["testcontainersVersion"] = "1.17.3" 33 | 34 | dependencies { 35 | implementation("org.springframework.boot:spring-boot-starter-aop") 36 | implementation("org.springframework.boot:spring-boot-starter-data-redis") 37 | implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive") 38 | 39 | implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") 40 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 41 | 42 | implementation("org.jetbrains.kotlin:kotlin-reflect") 43 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 44 | implementation("org.jetbrains.kotlin:kotlin-stdlib") 45 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") 46 | 47 | testImplementation("org.springframework.boot:spring-boot-starter-test") 48 | testImplementation("io.projectreactor:reactor-test") 49 | testImplementation("org.testcontainers:junit-jupiter") 50 | testImplementation("io.mockk:mockk:1.12.7") 51 | testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test") 52 | testImplementation("com.redis.testcontainers:testcontainers-redis-junit:1.6.2") 53 | } 54 | 55 | configurations { 56 | testImplementation { 57 | extendsFrom(compileOnly.get()) 58 | } 59 | } 60 | 61 | dependencyManagement { 62 | imports { 63 | mavenBom("org.testcontainers:testcontainers-bom:${property("testcontainersVersion")}") 64 | } 65 | } 66 | 67 | tasks.withType { 68 | kotlinOptions { 69 | freeCompilerArgs = listOf("-Xjsr305=strict", "-opt-in=kotlin.RequiresOptIn") 70 | jvmTarget = "17" 71 | } 72 | } 73 | 74 | tasks.withType { 75 | useJUnitPlatform() 76 | } 77 | 78 | tasks { 79 | jar { 80 | enabled = true 81 | archiveClassifier.set("") 82 | } 83 | 84 | bootJar { 85 | enabled = false 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /example/.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 | -------------------------------------------------------------------------------- /example/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.7.3" 5 | id("io.spring.dependency-management") version "1.0.13.RELEASE" 6 | id("org.jlleitschuh.gradle.ktlint") version "11.0.0" 7 | kotlin("jvm") version "1.6.21" 8 | kotlin("plugin.spring") version "1.6.21" 9 | } 10 | 11 | group = "com.dteknoloji" 12 | version = "0.0.1-SNAPSHOT" 13 | java.sourceCompatibility = JavaVersion.VERSION_17 14 | 15 | repositories { 16 | mavenCentral() 17 | maven { url = uri("https://jitpack.io") } 18 | } 19 | 20 | dependencies { 21 | implementation("org.springframework.boot:spring-boot-starter-data-redis") 22 | implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive") 23 | implementation("org.springframework.boot:spring-boot-starter-webflux") 24 | implementation("com.github.DogusTeknoloji:spring-redis-reactive-cache:1.0.3") 25 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 26 | implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") 27 | implementation("org.jetbrains.kotlin:kotlin-reflect") 28 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 29 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") 30 | testImplementation("org.springframework.boot:spring-boot-starter-test") 31 | testImplementation("io.projectreactor:reactor-test") 32 | } 33 | 34 | tasks.withType { 35 | kotlinOptions { 36 | freeCompilerArgs = listOf("-Xjsr305=strict") 37 | jvmTarget = "17" 38 | } 39 | } 40 | 41 | tasks.withType { 42 | useJUnitPlatform() 43 | } 44 | -------------------------------------------------------------------------------- /example/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DogusTeknoloji/spring-redis-reactive-cache/5078314d55994440471593028ec842936f966b78/example/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/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 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /example/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% equ 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% equ 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 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /example/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "reactive-cache-example" 2 | -------------------------------------------------------------------------------- /example/src/main/kotlin/com/dteknoloji/reactivecacheexample/ReactiveCacheExampleApplication.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.reactivecacheexample 2 | 3 | import com.dteknoloji.springredisreactivecache.annotation.EnableReactiveCaching 4 | import org.springframework.boot.autoconfigure.SpringBootApplication 5 | import org.springframework.boot.runApplication 6 | 7 | @SpringBootApplication 8 | @EnableReactiveCaching 9 | class ReactiveCacheExampleApplication 10 | 11 | fun main(args: Array) { 12 | runApplication(*args) 13 | } 14 | -------------------------------------------------------------------------------- /example/src/main/kotlin/com/dteknoloji/reactivecacheexample/Todo.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.reactivecacheexample 2 | 3 | data class Todo( 4 | val id: Int?, 5 | val title: String, 6 | val completed: Boolean 7 | ) 8 | -------------------------------------------------------------------------------- /example/src/main/kotlin/com/dteknoloji/reactivecacheexample/TodoApiClient.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.reactivecacheexample 2 | 3 | import org.springframework.context.annotation.Bean 4 | import org.springframework.context.annotation.Configuration 5 | import org.springframework.web.reactive.function.client.WebClient 6 | 7 | @Configuration 8 | class TodoApiClient { 9 | 10 | @Bean 11 | fun apiClient(): WebClient { 12 | return WebClient.builder() 13 | .baseUrl("https://jsonplaceholder.typicode.com/todos") 14 | .build() 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /example/src/main/kotlin/com/dteknoloji/reactivecacheexample/TodoController.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.reactivecacheexample 2 | 3 | import org.springframework.web.bind.annotation.DeleteMapping 4 | import org.springframework.web.bind.annotation.GetMapping 5 | import org.springframework.web.bind.annotation.PathVariable 6 | import org.springframework.web.bind.annotation.PostMapping 7 | import org.springframework.web.bind.annotation.RequestBody 8 | import org.springframework.web.bind.annotation.RequestMapping 9 | import org.springframework.web.bind.annotation.RestController 10 | 11 | @RestController 12 | @RequestMapping("/todos") 13 | class TodoController(private val todoService: TodoService) { 14 | 15 | @GetMapping("/{id}") 16 | suspend fun getById(@PathVariable id: Int): Todo { 17 | return todoService.getById(id, cacheFirst = true) 18 | } 19 | 20 | @PostMapping 21 | suspend fun create(@RequestBody todo: Todo): Todo { 22 | return todoService.create(todo) 23 | } 24 | 25 | @DeleteMapping("/{id}") 26 | suspend fun delete(@PathVariable id: Int) { 27 | todoService.delete(id) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /example/src/main/kotlin/com/dteknoloji/reactivecacheexample/TodoService.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.reactivecacheexample 2 | 3 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheEvict 4 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheGet 5 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCachePut 6 | import org.springframework.stereotype.Service 7 | import org.springframework.web.reactive.function.client.WebClient 8 | import org.springframework.web.reactive.function.client.awaitBodilessEntity 9 | import org.springframework.web.reactive.function.client.awaitBody 10 | 11 | @Service 12 | class TodoService(private val todoApiClient: WebClient) { 13 | 14 | @RedisReactiveCacheGet(key = "#id", keyPrefix = "TODO_", hashKey = "TODOS") 15 | suspend fun getById(id: Int, cacheFirst: Boolean = false): Todo { 16 | return todoApiClient.get() 17 | .uri { 18 | it.path("/{id}").build(id) 19 | } 20 | .retrieve() 21 | .awaitBody() 22 | } 23 | 24 | @RedisReactiveCachePut(keyPrefix = "TODO_", hashKey = "TODOS", expireDuration = "P1D") 25 | suspend fun create(todo: Todo): Todo { 26 | return todoApiClient.post() 27 | .bodyValue(todo) 28 | .retrieve() 29 | .awaitBody() 30 | } 31 | 32 | @RedisReactiveCacheEvict(keyPrefix = "TODO_", key = "#id", hashKey = "TODOS") 33 | suspend fun delete(id: Int) { 34 | todoApiClient.delete() 35 | .uri { 36 | it.path("/{id}").build(id) 37 | } 38 | .retrieve() 39 | .awaitBodilessEntity() 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /example/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | redis: 3 | host: localhost 4 | port: 6379 5 | 6 | logging: 7 | level: 8 | com.dteknoloji.springredisreactivecache.*: debug -------------------------------------------------------------------------------- /example/src/test/kotlin/com/dteknoloji/reactivecacheexample/ReactiveCacheExampleApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.reactivecacheexample 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.boot.test.context.SpringBootTest 5 | 6 | @SpringBootTest 7 | class ReactiveCacheExampleApplicationTests { 8 | 9 | @Test 10 | fun contextLoads() { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DogusTeknoloji/spring-redis-reactive-cache/5078314d55994440471593028ec842936f966b78/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.5-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 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /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% equ 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% equ 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 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "spring-redis-reactive-cache" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/annotation/EnableReactiveCaching.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.annotation 2 | 3 | import com.dteknoloji.springredisreactivecache.config.ReactiveCachingConfiguration 4 | import org.springframework.context.annotation.EnableAspectJAutoProxy 5 | import org.springframework.context.annotation.Import 6 | 7 | @Target(AnnotationTarget.CLASS) 8 | @Retention(AnnotationRetention.RUNTIME) 9 | @Import(ReactiveCachingConfiguration::class) 10 | @EnableAspectJAutoProxy 11 | annotation class EnableReactiveCaching() 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/annotation/RedisReactiveCacheEvict.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.annotation 2 | 3 | @Target(AnnotationTarget.FUNCTION) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | annotation class RedisReactiveCacheEvict( 6 | /** 7 | * Cache key prefix. 8 | * 9 | * Ex: CUSTOMER_ 10 | */ 11 | val keyPrefix: String, 12 | 13 | /** 14 | * Parameter name of the unique identifier. Must start with #. 15 | */ 16 | val key: String, 17 | 18 | /** 19 | * Redis hash key 20 | * 21 | * Ex: CUSTOMER_HASH 22 | */ 23 | val hashKey: String, 24 | ) 25 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/annotation/RedisReactiveCacheGet.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.annotation 2 | 3 | @Target(AnnotationTarget.FUNCTION) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | annotation class RedisReactiveCacheGet( 6 | 7 | /** 8 | * Cache key prefix. 9 | * 10 | * Ex: CUSTOMER_ 11 | */ 12 | val keyPrefix: String, 13 | 14 | /** 15 | * Parameter name of the unique identifier. Must start with #. 16 | */ 17 | val key: String, 18 | 19 | /** 20 | * Redis hash key 21 | * 22 | * Ex: CUSTOMER_HASH 23 | */ 24 | val hashKey: String, 25 | 26 | /** 27 | * Parameter name of the cache first setting. Must start with #. 28 | */ 29 | val cacheFirstParam: String = "#cacheFirst", 30 | ) 31 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/annotation/RedisReactiveCachePut.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.annotation 2 | 3 | @Target(AnnotationTarget.FUNCTION) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | annotation class RedisReactiveCachePut( 6 | 7 | /** 8 | * Cache key prefix. 9 | * 10 | * Ex: CUSTOMER_ 11 | */ 12 | val keyPrefix: String, 13 | 14 | /** 15 | * Redis hash key 16 | * 17 | * Ex: CUSTOMER_HASH 18 | */ 19 | val hashKey: String, 20 | 21 | /** 22 | * Cache expire duration. Must be a valid Java Duration string 23 | * 24 | * Ex: P1D 25 | */ 26 | val expireDuration: String, 27 | 28 | val idPropertyName: String = "id" 29 | ) 30 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/aspect/ReactiveRedisCacheAspect.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.aspect 2 | 3 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheEvict 4 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheGet 5 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCachePut 6 | import com.dteknoloji.springredisreactivecache.util.assertSuspending 7 | import com.dteknoloji.springredisreactivecache.util.proceedCoroutine 8 | import com.dteknoloji.springredisreactivecache.util.resolveParameterValue 9 | import com.dteknoloji.springredisreactivecache.util.resolveUniqueIdentifierValue 10 | import com.dteknoloji.springredisreactivecache.util.runCoroutine 11 | import com.fasterxml.jackson.databind.ObjectMapper 12 | import kotlinx.coroutines.CoroutineScope 13 | import kotlinx.coroutines.Deferred 14 | import kotlinx.coroutines.Dispatchers 15 | import kotlinx.coroutines.SupervisorJob 16 | import kotlinx.coroutines.async 17 | import kotlinx.coroutines.launch 18 | import kotlinx.coroutines.reactive.awaitFirstOrNull 19 | import kotlinx.coroutines.reactor.awaitSingle 20 | import org.aspectj.lang.ProceedingJoinPoint 21 | import org.aspectj.lang.annotation.Around 22 | import org.aspectj.lang.annotation.Aspect 23 | import org.aspectj.lang.reflect.MethodSignature 24 | import org.slf4j.LoggerFactory 25 | import org.springframework.data.redis.core.ReactiveRedisTemplate 26 | import org.springframework.data.redis.core.removeAndAwait 27 | import java.lang.reflect.Method 28 | import java.time.Duration 29 | import kotlin.reflect.KClass 30 | import kotlin.reflect.jvm.kotlinFunction 31 | 32 | @Aspect 33 | class ReactiveRedisCacheAspect( 34 | private val reactiveRedisTemplate: ReactiveRedisTemplate, 35 | private val objectMapper: ObjectMapper, 36 | private val cacheScope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) 37 | ) { 38 | 39 | private val logger = LoggerFactory.getLogger(ReactiveRedisCacheAspect::class.java) 40 | private val hashOps = reactiveRedisTemplate.opsForHash() 41 | 42 | @Around("execution(public * *(..)) && @annotation(com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCachePut)") 43 | fun redisReactiveCachePut(joinPoint: ProceedingJoinPoint): Any? { 44 | val method: Method = (joinPoint.signature as MethodSignature).method 45 | assertSuspending(method) 46 | val annotation: RedisReactiveCachePut = method.getAnnotation(RedisReactiveCachePut::class.java) 47 | 48 | return joinPoint.runCoroutine { 49 | joinPoint.proceedCoroutine()?.let { 50 | val id = it.resolveUniqueIdentifierValue(annotation.idPropertyName) 51 | putToCache("${annotation.keyPrefix}$id", annotation.hashKey, annotation.expireDuration, it) 52 | return@let it 53 | } ?: joinPoint.proceedCoroutine() 54 | } 55 | } 56 | 57 | @Around("execution(public * *(..)) && @annotation(com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheGet)") 58 | fun redisReactiveCacheGet(joinPoint: ProceedingJoinPoint): Any? { 59 | val method: Method = (joinPoint.signature as MethodSignature).method 60 | assertSuspending(method) 61 | val returnType = (method.kotlinFunction!!.returnType.classifier as KClass<*>).javaObjectType 62 | val annotation: RedisReactiveCacheGet = method.getAnnotation(RedisReactiveCacheGet::class.java) 63 | 64 | val id = resolveParameterValue(joinPoint, annotation.key) 65 | val cacheKey = "${annotation.keyPrefix}$id" 66 | val cacheFirst = resolveParameterValue(joinPoint, annotation.cacheFirstParam) as Boolean? ?: false 67 | 68 | return joinPoint.runCoroutine { 69 | if (cacheFirst) { 70 | getFromCacheAsync(cacheKey, annotation.hashKey, returnType).await() ?: getFromRealCall(joinPoint, cacheKey, annotation.hashKey, returnType) 71 | } else { 72 | logger.debug("Got cacheFirst false. Will ignore cache. Calling the real service. key: $cacheKey") 73 | getFromRealCall(joinPoint, cacheKey, annotation.hashKey, returnType) 74 | } 75 | } 76 | } 77 | 78 | @Around("execution(public * *(..)) && @annotation(com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheEvict)") 79 | fun redisReactiveCacheEvict(joinPoint: ProceedingJoinPoint): Any? { 80 | val method: Method = (joinPoint.signature as MethodSignature).method 81 | assertSuspending(method) 82 | val annotation: RedisReactiveCacheEvict = method.getAnnotation(RedisReactiveCacheEvict::class.java) 83 | 84 | val id = resolveParameterValue(joinPoint, annotation.key) 85 | 86 | return joinPoint.runCoroutine { 87 | removeFromCache("${annotation.keyPrefix}$id", annotation.hashKey) 88 | } 89 | } 90 | 91 | private fun getFromCacheAsync(key: String, hashKey: String, type: Class): Deferred { 92 | return cacheScope.async { 93 | val cachedValue: Any? = try { 94 | hashOps.get(key, hashKey).awaitFirstOrNull() 95 | } catch (ex: Exception) { 96 | logger.error("Redis threw exception while trying to get from cache", ex) 97 | null 98 | } 99 | 100 | if (cachedValue != null) { 101 | logger.debug("Returning from cache. key: $key") 102 | return@async objectMapper.convertValue(cachedValue, type) 103 | } 104 | 105 | logger.debug("Record doesn't exists on cache: $key") 106 | return@async null 107 | } 108 | } 109 | 110 | private suspend fun getFromRealCall(joinPoint: ProceedingJoinPoint, key: String, hashKey: String, type: Class): Any? { 111 | logger.debug("Getting from real call") 112 | return joinPoint.proceedCoroutine()?.let { 113 | putToCache(key, hashKey, "P1D", it) 114 | objectMapper.convertValue(it, type) 115 | } ?: objectMapper.convertValue(joinPoint.proceedCoroutine(), type) 116 | } 117 | 118 | private fun putToCache(key: String, hashKey: String, expireDuration: String, entity: Any) { 119 | cacheScope.launch { 120 | try { 121 | logger.debug("Putting to cache: key: $key") 122 | hashOps.put(key, hashKey, entity).awaitSingle() 123 | reactiveRedisTemplate.expire(key, Duration.parse(expireDuration)).awaitSingle() 124 | } catch (ex: Exception) { 125 | logger.error("Redis threw exception while trying to put to cache", ex) 126 | } 127 | } 128 | } 129 | 130 | private fun removeFromCache(key: String, hashKey: String) { 131 | cacheScope.launch { 132 | try { 133 | logger.debug("Removing from cache: key: $key") 134 | hashOps.removeAndAwait(key, hashKey) 135 | } catch (ex: Exception) { 136 | logger.error("Redis threw exception while trying to remove from cache", ex) 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/config/ReactiveCachingConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.config 2 | 3 | import com.dteknoloji.springredisreactivecache.aspect.ReactiveRedisCacheAspect 4 | import com.fasterxml.jackson.databind.ObjectMapper 5 | import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean 8 | import org.springframework.context.annotation.Bean 9 | import org.springframework.context.annotation.Configuration 10 | import org.springframework.context.annotation.Primary 11 | import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory 12 | import org.springframework.data.redis.core.ReactiveRedisTemplate 13 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer 14 | import org.springframework.data.redis.serializer.RedisSerializationContext 15 | import org.springframework.data.redis.serializer.StringRedisSerializer 16 | 17 | @Configuration 18 | @ConditionalOnClass(ReactiveRedisConnectionFactory::class) 19 | class ReactiveCachingConfiguration { 20 | 21 | @Bean 22 | @ConditionalOnMissingBean 23 | fun objectMapper() = jacksonObjectMapper() 24 | 25 | @Bean 26 | @Primary 27 | fun reactiveRedisTemplate( 28 | reactiveRedisConnectionFactory: ReactiveRedisConnectionFactory, 29 | objectMapper: ObjectMapper, 30 | ): ReactiveRedisTemplate { 31 | val serializer = Jackson2JsonRedisSerializer(Any::class.java) 32 | serializer.setObjectMapper(objectMapper) 33 | 34 | val serializationContext = RedisSerializationContext 35 | .newSerializationContext() 36 | .key(StringRedisSerializer()) 37 | .value(serializer) 38 | .hashKey(StringRedisSerializer()) 39 | .hashValue(serializer) 40 | .build() 41 | 42 | return ReactiveRedisTemplate(reactiveRedisConnectionFactory, serializationContext) 43 | } 44 | 45 | @Bean 46 | @ConditionalOnMissingBean 47 | fun reactiveRedisCacheAspect(reactiveRedisTemplate: ReactiveRedisTemplate, objectMapper: ObjectMapper) = 48 | ReactiveRedisCacheAspect(reactiveRedisTemplate, objectMapper) 49 | } 50 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/util/Extensions.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.util 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint 4 | import kotlin.coroutines.Continuation 5 | import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn 6 | import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn 7 | 8 | @Suppress("UNCHECKED_CAST") 9 | private val ProceedingJoinPoint.coroutineContinuation: Continuation 10 | get() = this.args.last() as Continuation 11 | 12 | private val ProceedingJoinPoint.coroutineArgs: Array 13 | get() = this.args.sliceArray(0 until this.args.size - 1) 14 | 15 | suspend fun ProceedingJoinPoint.proceedCoroutine( 16 | args: Array = this.coroutineArgs 17 | ): Any? = 18 | suspendCoroutineUninterceptedOrReturn { continuation -> 19 | this.proceed(args + continuation) 20 | } 21 | 22 | fun ProceedingJoinPoint.runCoroutine( 23 | block: suspend () -> Any? 24 | ): Any? = 25 | block.startCoroutineUninterceptedOrReturn(this.coroutineContinuation) 26 | -------------------------------------------------------------------------------- /src/main/kotlin/com/dteknoloji/springredisreactivecache/util/ReactiveCacheUtils.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.util 2 | 3 | import org.aspectj.lang.JoinPoint 4 | import org.aspectj.lang.reflect.MethodSignature 5 | import org.slf4j.LoggerFactory 6 | import java.lang.reflect.Method 7 | import kotlin.coroutines.Continuation 8 | import kotlin.reflect.full.memberProperties 9 | 10 | private val logger = LoggerFactory.getLogger("ReactiveCacheUtils") 11 | 12 | fun resolveParameterValue(joinPoint: JoinPoint, annotationKey: String): Any? { 13 | val method: Method = (joinPoint.signature as MethodSignature).method 14 | 15 | if (!annotationKey.startsWith('#')) throw IllegalArgumentException("Annotation key should start with # character") 16 | 17 | val resolvedValue = if (annotationKey.contains('.')) { 18 | val paramNameRegex = "(?<=#).*?(?=\\.)".toRegex() // matches between first '#' and '.' 19 | 20 | method.parameters.withIndex().find { parameter -> parameter.value.name == paramNameRegex.find(annotationKey)?.value } 21 | ?.let { parameterIndexedValue -> 22 | val param = joinPoint.args[parameterIndexedValue.index] 23 | param::class.memberProperties.find { it.name == annotationKey.substringAfter('.') }!!.getter.call(param)!! 24 | } 25 | } else { 26 | method.parameters.withIndex().find { parameter -> parameter.value.name == annotationKey.substringAfter('#') }?.let { 27 | joinPoint.args[it.index] 28 | } 29 | } 30 | 31 | if (resolvedValue == null) { 32 | logger.warn("Couldn't find expected parameter in ${method.name}. Expected $annotationKey but got null. Did you forget to add?") 33 | } 34 | 35 | return resolvedValue 36 | } 37 | 38 | fun isSuspending(method: Method): Boolean = method.parameters.lastOrNull()?.type?.isAssignableFrom(Continuation::class.java) == true 39 | 40 | fun assertSuspending(method: Method) { 41 | if (!isSuspending(method)) throw UnsupportedOperationException("Only suspending methods allowed") 42 | } 43 | 44 | fun Any.resolveUniqueIdentifierValue(propertyName: String = "id"): Any { 45 | return this::class.memberProperties.find { kProperty1 -> kProperty1.name == propertyName }!!.getter.call(this)!! 46 | } 47 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/TestUtils.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache 2 | 3 | import java.util.concurrent.TimeUnit 4 | import java.util.concurrent.locks.ReentrantLock 5 | 6 | private val lock = ReentrantLock() 7 | 8 | suspend fun waitUntilFetchData(block: suspend () -> Any?): Any { 9 | val condition = lock.newCondition() 10 | lock.lock() 11 | var result: Any? = null 12 | 13 | while (result == null) { 14 | condition.await(50, TimeUnit.MILLISECONDS) 15 | result = block() 16 | condition.signal() 17 | } 18 | lock.unlock() 19 | return result 20 | } 21 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/aspect/ReactiveRedisCacheAspectTest.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.aspect 2 | 3 | import com.dteknoloji.springredisreactivecache.dto.CacheableCustomer 4 | import com.dteknoloji.springredisreactivecache.service.CustomerTestService 5 | import com.fasterxml.jackson.databind.ObjectMapper 6 | import io.mockk.Ordering 7 | import io.mockk.coEvery 8 | import io.mockk.coVerify 9 | import io.mockk.every 10 | import io.mockk.mockk 11 | import io.mockk.mockkStatic 12 | import io.mockk.unmockkStatic 13 | import io.mockk.verify 14 | import kotlinx.coroutines.ExperimentalCoroutinesApi 15 | import kotlinx.coroutines.test.TestScope 16 | import kotlinx.coroutines.test.advanceUntilIdle 17 | import kotlinx.coroutines.test.runTest 18 | import org.junit.jupiter.api.BeforeEach 19 | import org.junit.jupiter.api.Test 20 | import org.springframework.aop.aspectj.annotation.AspectJProxyFactory 21 | import org.springframework.data.redis.core.ReactiveHashOperations 22 | import org.springframework.data.redis.core.ReactiveRedisTemplate 23 | import org.springframework.data.redis.core.removeAndAwait 24 | import reactor.core.publisher.Mono 25 | import java.time.Duration 26 | import java.util.UUID 27 | 28 | @OptIn(ExperimentalCoroutinesApi::class) 29 | class ReactiveRedisCacheAspectTest { 30 | 31 | private var testScope: TestScope = TestScope() 32 | private val proxyFactory = AspectJProxyFactory(CustomerTestService()) 33 | private val objectMapper = mockk() 34 | private val opsForHash = mockk> { 35 | every { put(ofType(), ofType(), ofType()) } returns Mono.just(true) 36 | every { get(ofType(), ofType()) } returns Mono.empty() 37 | } 38 | private val reactiveRedisTemplate: ReactiveRedisTemplate = mockk { 39 | every { opsForHash() } returns opsForHash 40 | every { expire(ofType(), ofType()) } returns Mono.just(true) 41 | } 42 | 43 | @BeforeEach 44 | fun setup() { 45 | testScope = TestScope() 46 | proxyFactory.addAspect(ReactiveRedisCacheAspect(reactiveRedisTemplate, objectMapper, testScope)) 47 | } 48 | 49 | @Test 50 | fun `when RedisReactiveCachePut annotated method executed by proxy it should put entity to redis cache`() = testScope.runTest { 51 | // Given 52 | val proxy: CustomerTestService = proxyFactory.getProxy() 53 | val id = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 54 | val dummyCacheableCustomer = CacheableCustomer(id) 55 | val key = "CUSTOMER_$id" 56 | 57 | // When 58 | proxy.create() 59 | advanceUntilIdle() 60 | 61 | // Then 62 | verify(Ordering.ORDERED) { 63 | opsForHash.put(key, "CUSTOMER_HASH", dummyCacheableCustomer) 64 | reactiveRedisTemplate.expire(key, Duration.parse("P1D")) 65 | } 66 | } 67 | 68 | @Test 69 | fun `when RedisReactiveCacheEvict annotated method executed by proxy it should remove entity from redis cache`() = testScope.runTest { 70 | // Given 71 | mockkStatic(opsForHash::removeAndAwait) 72 | coEvery { opsForHash.removeAndAwait(ofType(), ofType()) } returns 1 73 | val proxy: CustomerTestService = proxyFactory.getProxy() 74 | val id = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 75 | val key = "CUSTOMER_$id" 76 | 77 | // When 78 | proxy.delete(id) 79 | advanceUntilIdle() 80 | 81 | // Then 82 | coVerify { 83 | opsForHash.removeAndAwait(key, "CUSTOMER_HASH") 84 | } 85 | unmockkStatic(opsForHash::removeAndAwait) 86 | } 87 | 88 | @Test 89 | fun `when RedisReactiveCacheGet annotated method executed by proxy it should get entity from redis cache`() = testScope.runTest { 90 | // Given 91 | val proxy: CustomerTestService = proxyFactory.getProxy() 92 | val id = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 93 | val key = "CUSTOMER_$id" 94 | every { objectMapper.convertValue(ofType(), CacheableCustomer::class.java) } answers { firstArg() } 95 | 96 | // When 97 | proxy.getById(id, cacheFirst = true) 98 | advanceUntilIdle() 99 | 100 | // Then 101 | verify(Ordering.ORDERED) { 102 | opsForHash.get(key, "CUSTOMER_HASH") 103 | } 104 | } 105 | 106 | @Test 107 | fun `when RedisReactiveCacheGet annotated method executed by proxy it should get entity from real method and put to redis cache`() = testScope.runTest { 108 | // Given 109 | val proxy: CustomerTestService = proxyFactory.getProxy() 110 | val id = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 111 | val key = "CUSTOMER_$id" 112 | every { objectMapper.convertValue(ofType(), CacheableCustomer::class.java) } answers { firstArg() } 113 | 114 | // When 115 | proxy.getById(id, cacheFirst = false) 116 | advanceUntilIdle() 117 | 118 | // Then 119 | verify(Ordering.ORDERED) { 120 | opsForHash.put(key, "CUSTOMER_HASH", CacheableCustomer(id)) 121 | reactiveRedisTemplate.expire(key, Duration.parse("P1D")) 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/dto/CacheableCustomer.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.dto 2 | 3 | import java.util.UUID 4 | 5 | data class CacheableCustomer(val id: UUID, var name: String = "Jack", val surname: String = "Yago") 6 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/dto/DummyGetRequest.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.dto 2 | 3 | data class DummyGetRequest( 4 | val customerId: Long, 5 | ) 6 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/integration/IntegrationTest.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.integration 2 | 3 | import com.dteknoloji.springredisreactivecache.annotation.EnableReactiveCaching 4 | import com.dteknoloji.springredisreactivecache.aspect.ReactiveRedisCacheAspect 5 | import com.dteknoloji.springredisreactivecache.config.ReactiveCachingConfiguration 6 | import com.dteknoloji.springredisreactivecache.dto.CacheableCustomer 7 | import com.dteknoloji.springredisreactivecache.service.CustomerTestService 8 | import com.dteknoloji.springredisreactivecache.waitUntilFetchData 9 | import com.fasterxml.jackson.databind.ObjectMapper 10 | import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 11 | import com.redis.testcontainers.RedisContainer 12 | import com.redis.testcontainers.RedisContainer.DEFAULT_IMAGE_NAME 13 | import com.redis.testcontainers.RedisContainer.DEFAULT_TAG 14 | import kotlinx.coroutines.runBlocking 15 | import org.junit.jupiter.api.Assertions.assertEquals 16 | import org.junit.jupiter.api.Test 17 | import org.junit.jupiter.api.TestInstance 18 | import org.springframework.beans.factory.annotation.Autowired 19 | import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration 20 | import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration 21 | import org.springframework.boot.test.context.SpringBootTest 22 | import org.springframework.boot.test.context.TestConfiguration 23 | import org.springframework.context.annotation.Bean 24 | import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory 25 | import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory 26 | import org.springframework.data.redis.core.ReactiveRedisTemplate 27 | import org.springframework.data.redis.core.getAndAwait 28 | import org.springframework.data.redis.core.putAndAwait 29 | import org.springframework.test.context.ContextConfiguration 30 | import org.testcontainers.junit.jupiter.Container 31 | import org.testcontainers.junit.jupiter.Testcontainers 32 | import java.util.UUID 33 | 34 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 35 | @SpringBootTest 36 | @ContextConfiguration( 37 | classes = [ 38 | IntegrationTest.TestConfig::class, 39 | ReactiveCachingConfiguration::class, 40 | ReactiveRedisCacheAspect::class, 41 | RedisReactiveAutoConfiguration::class, 42 | RedisAutoConfiguration::class, 43 | CustomerTestService::class 44 | ] 45 | ) 46 | @Testcontainers 47 | class IntegrationTest { 48 | 49 | @Autowired 50 | private lateinit var reactiveRedisTemplate: ReactiveRedisTemplate 51 | 52 | @Autowired 53 | private lateinit var customerTestService: CustomerTestService 54 | 55 | @Autowired 56 | private lateinit var objectMapper: ObjectMapper 57 | 58 | @Test 59 | fun `when a method invoked that annotated with RedisReactiveCachePut it should put the return value to redis`(): Unit = runBlocking { 60 | // Given 61 | val customerId = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 62 | val expected = CacheableCustomer(id = customerId) 63 | 64 | // When 65 | val actual = customerTestService.create() 66 | 67 | // Then 68 | val cache = waitUntilFetchData { 69 | reactiveRedisTemplate.opsForHash().getAndAwait("CUSTOMER_$customerId", "CUSTOMER_HASH") 70 | } 71 | 72 | assertEquals(expected, actual) 73 | assertEquals(expected, objectMapper.convertValue(cache, CacheableCustomer::class.java)) 74 | } 75 | 76 | @Test 77 | fun `when a method invoked that annotated with RedisReactiveCacheGet it should get from redis`(): Unit = runBlocking { 78 | // Given 79 | val customerId = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 80 | val expected = CacheableCustomer(id = customerId) 81 | reactiveRedisTemplate.opsForHash().putAndAwait("CUSTOMER_$customerId", "CUSTOMER_HASH", expected) 82 | 83 | // When 84 | val actual = customerTestService.getById(customerId, true) 85 | 86 | // Then 87 | assertEquals(expected, actual) 88 | } 89 | 90 | @TestConfiguration 91 | @EnableReactiveCaching 92 | class TestConfig { 93 | 94 | @Bean 95 | fun objectMapper(): ObjectMapper = jacksonObjectMapper() 96 | 97 | @Container 98 | private val redisContainer = RedisContainer(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG)) 99 | 100 | init { 101 | redisContainer.start() 102 | } 103 | 104 | @Bean 105 | fun reactiveRedisConnectionFactory(): ReactiveRedisConnectionFactory { 106 | return LettuceConnectionFactory("localhost", redisContainer.firstMappedPort) 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/service/CustomerTestService.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.service 2 | 3 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheEvict 4 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheGet 5 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCachePut 6 | import com.dteknoloji.springredisreactivecache.dto.CacheableCustomer 7 | import org.springframework.stereotype.Service 8 | import java.util.UUID 9 | 10 | @Service 11 | class CustomerTestService { 12 | 13 | @RedisReactiveCachePut(keyPrefix = "CUSTOMER_", hashKey = "CUSTOMER_HASH", expireDuration = "P1D") 14 | suspend fun create(): CacheableCustomer { 15 | return CacheableCustomer(id) 16 | } 17 | 18 | @RedisReactiveCacheEvict(keyPrefix = "CUSTOMER_", hashKey = "CUSTOMER_HASH", key = "#id") 19 | suspend fun delete(id: UUID) { 20 | } 21 | 22 | @RedisReactiveCacheGet(keyPrefix = "CUSTOMER_", hashKey = "CUSTOMER_HASH", key = "#id") 23 | suspend fun getById(id: UUID, cacheFirst: Boolean = false): CacheableCustomer { 24 | return CacheableCustomer(id, "Jack") 25 | } 26 | 27 | companion object { 28 | private val id = UUID.fromString("be12698e-e2ab-42d4-96bf-d1699610a2db") 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/kotlin/com/dteknoloji/springredisreactivecache/util/ReactiveCacheUtilsTest.kt: -------------------------------------------------------------------------------- 1 | package com.dteknoloji.springredisreactivecache.util 2 | 3 | import com.dteknoloji.springredisreactivecache.annotation.RedisReactiveCacheGet 4 | import com.dteknoloji.springredisreactivecache.dto.CacheableCustomer 5 | import com.dteknoloji.springredisreactivecache.dto.DummyGetRequest 6 | import io.mockk.every 7 | import io.mockk.mockk 8 | import org.aspectj.lang.JoinPoint 9 | import org.aspectj.lang.reflect.MethodSignature 10 | import org.junit.jupiter.api.Assertions.assertEquals 11 | import org.junit.jupiter.api.Assertions.assertTrue 12 | import org.junit.jupiter.api.Test 13 | import java.util.UUID 14 | import kotlin.reflect.full.declaredFunctions 15 | import kotlin.reflect.jvm.javaMethod 16 | 17 | class ReactiveCacheUtilsTest { 18 | 19 | @Test 20 | fun testResolveParameterValue() { 21 | // Given 22 | val annotationKey = "#request.customerId" 23 | val method = ReactiveCacheUtilsTest::class.declaredFunctions.find { it -> it.name == "get" }!!.javaMethod 24 | val methodSignature = mockk() { every { this@mockk.method } returns method } 25 | 26 | val joinPoint = mockk { 27 | every { args } returns arrayOf(DummyGetRequest(15L)) 28 | every { signature } returns methodSignature 29 | } 30 | 31 | // When 32 | val actual = resolveParameterValue(joinPoint, annotationKey) 33 | 34 | // Then 35 | assertEquals(15L, actual) 36 | } 37 | 38 | @Test 39 | fun `when resolveParameterValue for primitive object it should successfully resolve param value`() { 40 | // Given 41 | val annotationKey = "#customerId" 42 | val method = mockk { 43 | every { method } returns mockk() { 44 | every { parameters } returns arrayOf( 45 | mockk { 46 | every { name } returns "customerId" 47 | } 48 | ) 49 | } 50 | } 51 | val joinPoint = mockk { 52 | every { args } returns arrayOf(16L) 53 | every { signature } returns method 54 | } 55 | 56 | // When 57 | val actual = resolveParameterValue(joinPoint, annotationKey) 58 | 59 | // Then 60 | assertEquals(16L, actual) 61 | } 62 | 63 | @Test 64 | fun `when isSuspending is called it should check if method is suspending`() { 65 | // Given 66 | val method = ReactiveCacheUtilsTest::class.declaredFunctions.find { it -> it.name == "get" }!!.javaMethod!! 67 | 68 | // When 69 | val actual = isSuspending(method) 70 | 71 | // Then 72 | assertTrue(actual) 73 | } 74 | 75 | @Test 76 | fun `when resolveUniqueIdentifierValue is called it should resolve id value`() { 77 | // Given 78 | val customerId = UUID.randomUUID() 79 | val entity = CacheableCustomer(id = customerId) 80 | 81 | // When 82 | val actual = entity.resolveUniqueIdentifierValue() 83 | 84 | // Then 85 | assertEquals(customerId, actual) 86 | } 87 | 88 | @RedisReactiveCacheGet(keyPrefix = "CUSTOMER_", hashKey = "CUSTOMER_HASH", key = "#request.customerId") 89 | private suspend fun get(request: DummyGetRequest, cacheFirst: Boolean = false): CacheableCustomer { 90 | return CacheableCustomer(UUID.randomUUID(), "Jack") 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | com.dteknoloji.springredisreactivecache: debug --------------------------------------------------------------------------------