├── .gitignore ├── .idea ├── .gitignore ├── gradle.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml ├── uiDesigner.xml └── vcs.xml ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── image ├── redis-create.png └── redis-project.png ├── readme.md ├── redis-crud ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── villainscode │ │ └── redis │ │ ├── RedisCrudApplication.java │ │ ├── config │ │ └── RedisConfig.java │ │ ├── keygenerate │ │ └── KeyGenerateService.java │ │ ├── message │ │ ├── MessageController.java │ │ ├── RedisPublisher.java │ │ └── RedisSubscriber.java │ │ └── rediskey │ │ ├── RedisKeyController.java │ │ └── RedisKeyService.java │ └── resources │ ├── application.properties │ └── logback-spring.xml ├── redis-pub ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── villainscode │ │ └── redis │ │ ├── RedisPubApplication.java │ │ ├── config │ │ └── RedisConfiguration.java │ │ ├── model │ │ └── OrderQueue.java │ │ └── publisher │ │ ├── OrderService.java │ │ ├── PublisherController.java │ │ └── RedisPublisher.java │ └── resources │ └── application.properties ├── redis-sample ├── build.gradle └── src │ └── main │ ├── java │ ├── com │ │ └── villainscode │ │ │ └── redis │ │ │ └── SpringRedisApplication.java │ └── message │ │ └── Receiver.java │ └── resources │ └── logback-spring.xml ├── redis-sub ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── villainscode │ │ └── redis │ │ ├── RedisSubApplication.java │ │ ├── config │ │ ├── RedisConfiguration.java │ │ └── SubscriberConfiguration.java │ │ └── subscriber │ │ ├── OrderDTO.java │ │ └── SubscriberEventListener.java │ └── resources │ └── application.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | 3 | 4 | build/ 5 | !gradle/wrapper/gradle-wrapper.jar 6 | !**/src/main/**/build/ 7 | !**/src/test/**/build/ 8 | 9 | ### IntelliJ IDEA ### 10 | .idea/modules.xml 11 | .idea/jarRepositories.xml 12 | .idea/compiler.xml 13 | .idea/libraries/ 14 | *.iws 15 | *.iml 16 | *.ipr 17 | out/ 18 | !**/src/main/**/out/ 19 | !**/src/test/**/out/ 20 | 21 | ### Eclipse ### 22 | .apt_generated 23 | .classpath 24 | .factorypath 25 | .project 26 | .settings 27 | .springBeans 28 | .sts4-cache 29 | bin/ 30 | !**/src/main/**/bin/ 31 | !**/src/test/**/bin/ 32 | 33 | ### NetBeans ### 34 | /nbproject/private/ 35 | /nbbuild/ 36 | /dist/ 37 | /nbdist/ 38 | /.nb-gradle/ 39 | 40 | ### VS Code ### 41 | .vscode/ 42 | 43 | ### Mac OS ### 44 | .DS_Store -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 20 | 21 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.3.1' 4 | id 'io.spring.dependency-management' version '1.1.5' 5 | } 6 | 7 | group = 'com.villainscode' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | sourceCompatibility = '17' 12 | } 13 | 14 | configurations { 15 | compileOnly { 16 | extendsFrom annotationProcessor 17 | } 18 | } 19 | 20 | // 하위 프로젝트 모듈의 공통 플러그인 및 의존성 정의 21 | subprojects { 22 | apply plugin: 'java-library' 23 | apply plugin: 'idea' 24 | apply plugin: 'org.springframework.boot' 25 | apply plugin: 'io.spring.dependency-management' 26 | apply plugin: 'java' 27 | compileJava.options.encoding = 'UTF-8' 28 | sourceCompatibility = '17' 29 | 30 | task wrapper(type: Wrapper) { 31 | gradleVersion = '8.1.1' 32 | } 33 | 34 | repositories { 35 | mavenCentral() 36 | } 37 | 38 | dependencies { 39 | implementation 'org.springframework.boot:spring-boot-starter-data-redis' 40 | compileOnly 'org.projectlombok:lombok' 41 | developmentOnly 'org.springframework.boot:spring-boot-devtools' 42 | annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' 43 | annotationProcessor 'org.projectlombok:lombok' 44 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 45 | } 46 | 47 | 48 | tasks.named('test') { 49 | useJUnitPlatform() 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/villainscode/Spring-Redis/240aecb6b23ecc56e4594068ad0bb1c66f66e0a6/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jul 10 13:37:39 KST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /image/redis-create.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/villainscode/Spring-Redis/240aecb6b23ecc56e4594068ad0bb1c66f66e0a6/image/redis-create.png -------------------------------------------------------------------------------- /image/redis-project.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/villainscode/Spring-Redis/240aecb6b23ecc56e4594068ad0bb1c66f66e0a6/image/redis-project.png -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Spring Redis Quick Guide 2 | 3 | > 본 내용은 한빛미디어에서 출간한 책(개발자 기술 면접 노트)의 일부 내용을 보강하기 위해서 만든 Redis 활용 예제입니다.
4 | > 책의 분량상 코드나 이론등의 내용을 다 담아내지 못하였기에 본 문서로 추가적인 설명을 진행합니다.
5 | > 만약 내용에 문제가 있거나 오/탈자가 있을 경우 villainscode@gmail.com으로 메일 부탁드립니다. 6 | > 7 | > 8 | > - Instagram - [https://www.instagram.com/codevillains](https://www.instagram.com/codevillains) 9 | > - email - [villainscode@gmail.com](mailto:villainscode@gmail.com) 10 | > - Yes24 - https://www.yes24.com/Product/Goods/125554439 11 | > - KyoboBooks - https://product.kyobobook.co.kr/detail/S000212738756 12 | 13 | ## 책 소개 14 | 15 | 16 | ### [연봉의 앞자리를 바꾸는] 개발자 기술면접 노트 17 | - 2024.03.25, 한빛미디어, 이남희(codevillain) 저 18 | 19 | 20 | 21 | 22 | > **신입 및 주니어 개발직군의 취업 및 이직을 위한 가이드** 23 | > 24 | > 서류 작성 방법부터, 유망한 회사를 찾는 방법, 코딩 테스트와 기술 면접을 준비하기 위해 알아야 할 개념들을 어떤 방식으로 접근해야 하는지 설명했습니다. 25 | > 26 | > 특히 면접에서 면접관이 던지는 질문의 의도와 해당 질문에 올바르게 답변하기 위한 실질적인 대처방법에 대해서 기술하였습니다. 27 | > 아울러 기술면접을 넘어 인성면접에서 가져야할 마음가짐과 리더십 원칙, 정답이 없는 질문에 대처하기 위한 사례들을 소개하였습니다. 28 | > 29 | > 취업 및 이직의 상황에서 본인이 준비하고 있는 방향이 맞는지 점검하고 커리어 패스를 어떻게 설계해야 하는지 실천 가능한 방법을 제시함으로서 도움을 주고자 하였습니다. 30 | 31 | 32 | # 인프런 강의 33 | 34 | 35 | 36 | - [시니어면접관이 알려주는 개발자 취업과 이직, 한방에 해결하기 이론편](https://www.inflearn.com/course/%EC%8B%9C%EB%8B%88%EC%96%B4-%EB%A9%B4%EC%A0%91%EA%B4%80-%EC%95%8C%EB%A0%A4%EC%A3%BC%EB%8A%94-%EC%B7%A8%EC%97%85-%EC%9D%B4%EC%A7%81-%EC%9D%B4%EB%A1%A0) 37 | - [시니어면접관이 알려주는 개발자 취업과 이직, 한방에 해결하기 실전편](https://www.inflearn.com/course/%EC%8B%9C%EB%8B%88%EC%96%B4-%EB%A9%B4%EC%A0%91%EA%B4%80-%EC%95%8C%EB%A0%A4%EC%A3%BC%EB%8A%94-%EC%B7%A8%EC%97%85-%EC%9D%B4%EC%A7%81-%EC%8B%A4%EC%A0%84) 38 | 39 | 40 | 41 | 42 | # Redis 43 | 44 | 45 | Redis는 인메모리 데이터 구조 저장소로, 매우 빠른 속도로 데이터를 조회/저장할 수 있다. 46 | 47 | key, value 저장소로 유명하지만 단순한 key-value 저장소를 넘어 다양한 데이터 구조(문자열, 리스트, 해시, 셋 등)를 지원하며, 주로 캐싱 시스템으로 사용되어 데이터베이스 부하를 줄이고 애플리케이션 성능을 향상시칸다. 48 | 49 | Redis는 싱글 스레드 이벤트 루프 방식으로 동작하며, 클라이언트가 실행한 명령어들을 이벤트 큐에 적재하고 하나씩 처리한다. 이 방식은 초당 수만 건의 연산을 처리할 수 있는 높은 성능을 제공한다. 50 | 데이터 영속성은 AOF(Append Only File)와 RDB(Redis Database) 두 가지 방식으로 제공된다. 51 | 일반적으로 RDB 방식으로 일별 백업 데이터를 만들고, 그 이후부터는 AOF 형태로 당일 변경사항을 백업하는 형태로 영속성을 유지한다. 52 | 53 | 또한, Redis는 복제 및 클러스터링 기능을 통해 고가용성과 확장성을 제공하며, Pub/Sub 메시징 시스템과 트랜잭션 기능도 지원한다. 메모리 관리를 위해 다양한 정책(예: LRU, LFU)을 제공하여 제한된 메모리 환경에서도 효율적으로 동작할 수 있다 54 | 55 | ## 아키텍처 56 | 57 | 58 | 일반적인 Replication 세트로 구성해도 무방하지만 센티넬(Sentinel) 이나 클러스터를 구축함으로서, 고가용성 (HA, High Availability)와 Failover를 구성할 수 있다. 59 | 60 | 센티넬의 경우 센티넬 서버로 클라이언트가 연결하며, 센티넬이 마스터 서버들에게 명령어를 질의한다. 이 과정에서 모니터링이 되어야 하므로 3대 이상의 홀수로 마스터와 레플리카를 구성하는 것이 일반적이며, 장애 발생시 센티넬이 서버들의 동의 절차를 진행하여 (Quorum, 정족수) 마스터 서버를 제외하고 장애 복구 절차를 진행한다. 61 | 62 | 클러스터의 경우 클러스터에 포함된 노드들이 서로 통신하면서 HA를 유지하며, 샤딩 등의 분산 저장이 가능하다. (Hash 알고리즘) 63 | 64 | 스프링 애플리케이션 클라이언트는 레디스 클러스터의의 노드 중 하나라도 연결되면 클러스터 전체 정보를 확인할 수 있다. 65 | 따라서 운영중 증설을 하더라도 스프링 설정을 변경할 필요가 없다. 66 | 67 | ## 설치(MacOS, brew 설치 환경 기준) 68 | 69 | > $ brew install redis 70 | > 71 | 72 | ## 실행 73 | 74 | > $ brew services start redis or redis-server (foreground 실행) 75 | > 76 | > $ brew services stop redis or foreground 실행 화면에서 Ctrl + c 77 | > 78 | > $ brew services restart redis 79 | 80 | ## 일반 커맨드 81 | 82 | ### 자료의 저장과 조회 83 | 84 | ```jsx 85 | > SET Hello world // 저장 86 | ``` 87 | 88 | ```jsx 89 | > GET Hello // 조회 90 | ``` 91 | 92 | NX 옵션 : 지정한 키가 없을 때에만 새로운 키를 생성 (SET Hello newWorld NX) 93 | 94 | XX 옵션 : 키가 있을 때에만 새로운 값으로 덮어씀 (SET Hello newWorld XX) 95 | 96 | ### String 97 | 자료구조이지만 숫자 형태도 저장 가능하고 INCR이나 INCRBY 를 이용하여 1씩 증가시키거나 입력한 값만큼 증가시킬수 있다. 98 | 99 | ```jsx 100 | > SET counter 100 101 | > incr counter 102 | (integer) 101 103 | > incrby counter 50 104 | (integer) 151 105 | ``` 106 | 107 | ### MSET 108 | MGET으로 여러 키를 조작할 수 있다. 109 | 110 | ```jsx 111 | > MSET a 10 b 20 c 30 112 | OK 113 | > MGET a b c 114 | 1) "10" 115 | 2) "20" 116 | 3) "30" 117 | ``` 118 | 119 | ### LIST 타입의 조작 120 | List 타입(배열)의 경우 LPUSH(head)를 이용해 List의 왼쪽에 데이터를 삽입하고, RPUSH(tail)을 통해 List의 오른쪽에 데이터를 삽입한다. 121 | 122 | ```jsx 123 | > LPUSH mylist e 124 | (integer) 1 125 | > RPUSH mylist b 126 | (integer) 2 127 | > LRANGE mylist 0 -1 128 | 1) "e" 129 | 2) "b" 130 | ``` 131 | 132 | LRANGE를 통해 시작과 끝 인덱스를 조회할 수 있다. 133 | 134 | LPOP을 이용하여 기본삭제 (맨 앞)를 하거나 지정된 수 만큼 삭제 할 수 있다. 135 | 136 | LTRIM의 경우 지정된 두 범위만 남기고 나머지는 삭제한다. 137 | 138 | ```jsx 139 | LPOP mylist 140 | "A" 141 | > LRANGE mylist 0 -1 142 | 1) "B" 143 | 2) "C" 144 | 3) "A" 145 | 4) "D" 146 | 5) "e" 147 | 6) "b" 148 | > LPOP mylist 6 149 | 1) "B" 150 | 2) "C" 151 | 3) "A" 152 | 4) "D" 153 | 5) "e" 154 | 6) "b" 155 | > LRANGE mylist 0 -1 156 | (empty array) 157 | > LPUSH mylist D A C B A 158 | (integer) 5 159 | > LTRIM mylist 0 1 160 | OK 161 | > LRANGE mylist 0 -1 162 | 1) "A" 163 | 2) "B" 164 | ``` 165 | 166 | LINSERT를 통해 원하는 데이터 앞(before) 혹은 뒤(after)에 데이터를 추가할 수 있다. 167 | 168 | ```jsx 169 | > LINSERT mylist BEFORE B C 170 | (integer) 3 171 | > LRANGE mylist 0 -1 172 | 1) "A" 173 | 2) "C" 174 | 3) "B" 175 | ``` 176 | 177 | LSET을 통해 지정된 인덱스에 신규로 입력하여 덮어쓸 수 있다 178 | 179 | ```jsx 180 | > LSET mylist 1 D 181 | > LRANGE mylist 0 -1 182 | 1) "A" 183 | 2) "D" 184 | 3) "B" 185 | ``` 186 | 187 | LINDEX 를 통해 원하는 인덱스의 데이터를 조회할 수 있다. 188 | 189 | ```jsx 190 | > LINDEX mylist 2 191 | "B" 192 | ``` 193 | 194 | ### HASH 195 | 196 | Key, Value에서 Value의 구조 역시 필드와 값으로 이루어진 아이템 집합이다. 197 | 198 | HSET 커맨드를 이용해서 아이템들을 저장할 수 있으며, HGET을 통해 조회할 수 있다. 199 | 200 | HMGET으로 여러 필드를 조회할 수 있고, HGETALL을 통해 hash의 모든 필드를 반환받을 수 있다. 201 | 202 | ```jsx 203 | > HSET Product1 name "samsung" 204 | (integer) 1 205 | > HSET Product1 device "gal 22" 206 | (integer) 1 207 | > HSET Product1 version "2021" 208 | (integer) 1 209 | > HSET Product2 name "apple" device "iphone 11 pro" version "2022" 210 | ``` 211 | 212 | ```jsx 213 | > HGET Product1 name 214 | "samsung" 215 | > HMGET Product2 name device 216 | 1) "apple" 217 | 2) "iphone 11 pro" 218 | > HGETALL Product1 219 | 1) "name" 220 | 2) "samsung" 221 | 3) "device" 222 | 4) "gal 22" 223 | 5) "version" 224 | 6) "2021" 225 | ``` 226 | 227 | ### SET 228 | 229 | 정렬되지 않고 중복 저장이 되지 않는 문자열이다. 230 | 231 | SADD로 Set에 저장할 수 있으며 SMEMBERS로 Set 자료를 볼 수 있다. 232 | 233 | SREM으로 원하는 데이터를 삭제할 수 있고, SPOP으로 내부 아이템을 반환하고 삭제할 수 있다. 234 | 235 | 합집합은 SUNION, 교집합은 SINTER, 차집합은 SDIFF로 수행할 수 있다. 236 | 237 | ```jsx 238 | > SADD myset a 239 | (integer) 1 240 | > SADD myset a a a b b b c c c 241 | (integer) 2 242 | > SMEMBERS myset 243 | 1) "a" 244 | 2) "b" 245 | 3) "c" 246 | > SREM myset b 247 | (integer) 1 248 | > SMEMBERS myset 249 | 1) "a" 250 | 2) "c" 251 | > SPOP myset 252 | "a" 253 | > SMEMBERS myset 254 | 1) "c" 255 | ``` 256 | 257 | ```jsx 258 | > SADD set1 a b c d e 259 | (integer) 5 260 | > SADD set2 d e f g h 261 | (integer) 5 262 | > SINTER set1 set2 263 | 1) "d" 264 | 2) "e" 265 | > SDIFF set1 set2 266 | 1) "a" 267 | 2) "b" 268 | 3) "c" 269 | > SDIFF set2 set1 270 | 1) "f" 271 | 2) "g" 272 | 3) "h" 273 | ``` 274 | 275 | ### Sorted Set 276 | 277 | 스코어값에 따라 정렬되는 문자열. 모든 아이템은 스코어-값 쌍으로 저장되며 저장시 스코어로 정렬 처리된다. 278 | 279 | ```jsx 280 | > ZADD score:1 100 user:B 281 | (integer) 1 282 | > ZADD score:1 150 user:A 150 user:C 200 user:F 300 user:E 283 | (integer) 4 284 | > ZRANGE score:1 1 3 285 | 1) "user:A" 286 | 2) "user:C" 287 | 3) "user:F" 288 | > ZRANGE score:1 100 150 BYSCORE 289 | 1) "user:B" 290 | 2) "user:A" 291 | 3) "user:C" 292 | ``` 293 | 294 | 그밖에 Bitmap이나 Hyperloglog, Geospatial(위경도), Stream(메시지브로커) 등이 있다. 295 | 296 | ## Key 관련 커맨드 297 | 298 | 299 | ### 키 조회 300 | 301 | ```jsx 302 | > EXISTS key-name 303 | ``` 304 | 305 | ### 전체 키 조회 306 | 307 | ```jsx 308 | > KEYS [pattern] | * // 패턴 조회 혹은 모든 키 조회 309 | - KEYS 수행 비용은 높기 때문에 수십만개의 키 정보를 반환하는 것은 health check 응답이 없어 페일오버가 날 수 있다. (다른 커맨드도 사용불가) 310 | ``` 311 | 312 | ### Pattern 스타일 313 | 314 | - h?llo → hello, hallo 매칭 315 | - h*llo → hllo, heeello 매칭 316 | - h[ae]llo → hello, hallo 매칭, hillo는 매칭 불가 317 | - h[^e]llo → hallo, hbllo 매칭, hello는 매칭 불가 318 | - h[a-b]llo → hallo, hbllo 매칭 319 | 320 | ### 키 변경 321 | 322 | ```jsx 323 | > RENAME key newKey 324 | > RENAMENX key newKey 325 | ``` 326 | 327 | ### 키 삭제 328 | 329 | ```jsx 330 | > FLUSHALL [sync | async] 331 | or 332 | > DEL key [key-name] 333 | or 334 | > UNLINK key [key-name] 335 | ``` 336 | 337 | ### DEL 338 | DEL 의 경우 동기적으로 수행하기 때문에 레디스 인스턴스에 영향을 주고, 이 때문에 가급적 DEL 보다는 UNLINK로 처리해야 백그라운드로 키를 삭제하여 성능상 이슈가 없게 된다. 339 | 340 | 키 만료 지정 341 | 342 | ```jsx 343 | > EXPIRE key secontd [NX | XX | GT | LT] 344 | > EXPIRETIME key // 키 삭제 시간 반환, 만료시간 없을 경우 -1, 키 없을 경우 -2 반환 345 | ``` 346 | 347 | TTL의 경우 키의 만료시간을 반환한다. 348 | 349 | ```jsx 350 | > TTL key // 몇 초 뒤에 만료되는지 반환, 만료시간 없을 경우 -1, 키 없을 경우 -2 반환 351 | ``` 352 | 353 | ## Geospatial Index (위치 데이터) 354 | 355 | 356 | ### GEO SET 357 | 358 | 위치 정보를 경도와 위도 쌍으로 저장하며, 내부적으로 sorted set 구조로 저장한다. 359 | 360 | ```jsx 361 | > GETADD user 20.123123123 12.2133255345 362 | ``` 363 | 364 | 특정 식당을 레스토랑이라는 키에 경도, 위도, 식당 이름순으로 저장할 경우 아래와 같다. 365 | 366 | ```jsx 367 | > GEOADD restaurant 30.0123123 34.123123354 pangyo // 저장 368 | 369 | > GEOPOS restaurant pangyo // 저장된 데이터 370 | 1) 1) "30.01231223344802856" 371 | 2) "34.12312216686382982" 372 | 373 | > GEOSEARCH restaurant FROMLONLAT 30.0123123 34.123123354 byradius 1km // FROMLONLAT 으로 경도, 위도 지정 후 byradius 로 반경 1km 조회 374 | > GEOSEARCH key FROMMEMBER member bybox 4 2 km // 동일한 위경도 값 기준으로 witth 와 height에 대항하는 데이터 검색 (직사각형) 375 | ``` 376 | 377 | 그밖에 레디스를 캐시로 사용하거나 세션 스토어로 사용하거나 메시지 브로커 등으로 활용할 수 있다. 378 | 379 | ## Redis 모니터링 380 | ### INFO 381 | Redis 서버의 전반적인 상태를 확인할 수 있는 가장 기본적인 명령어이다. 382 | ```jsx 383 | > INFO 384 | ``` 385 | 이 명령어는 서버, 클라이언트, 메모리, 영속성 등 다양한 섹션의 정보를 제공한다. 386 | 387 | ### MONITOR 388 | 실시간으로 Redis 서버에서 처리되는 명령어를 볼 수 있다. 389 | 390 | ```jsx 391 | > MONITOR 392 | ``` 393 | 주의: 프로덕션 환경에서는 성능에 영향을 줄 수 있으므로 주의해서 사용해야 한다. 394 | 395 | ### SLOWLOG 396 | 설정된 실행 시간 임계값을 초과한 명령어들의 로그를 확인할 수 있다. 397 | 398 | ```jsx 399 | > SLOWLOG GET [number] 400 | ``` 401 | 402 | ### 외부 모니터링 도구 403 | 404 | - Redis-cli: 기본 제공되는 CLI 도구로, 다양한 모니터링 명령어를 지원 405 | - Redis-stat: Redis 서버의 실시간 통계를 보여주는 CLI 도구 406 | - Redis Commander: 웹 기반의 Redis 관리 도구로, 데이터 조회 및 수정이 가능 407 | - Prometheus + Grafana: 메트릭 수집 및 시각화를 위한 강력한 조합 408 | 409 | ### 주요 모니터링 지표 410 | - 메모리 사용량 411 | - 연결된 클라이언트 수 412 | - 초당 처리되는 명령어 수 413 | - 키스페이스 히트/미스 비율 414 | - 네트워크 대역폭 사용량 415 | 416 | ## Redis 실제 사용 사례 417 | 418 | ### 세션 저장소 419 | 420 | 웹 애플리케이션에서 사용자 세션 정보를 Redis에 저장하여 빠른 접근과 분산 환경에서의 세션 공유를 구현할 수 있다. 421 | 422 | ```java 423 | @Configuration 424 | @EnableRedisHttpSession 425 | public class SessionConfig { 426 | 427 | @Bean 428 | public LettuceConnectionFactory connectionFactory() { 429 | return new LettuceConnectionFactory(); 430 | } 431 | } 432 | 433 | // 사용 예 434 | @RestController 435 | public class SessionController { 436 | 437 | @GetMapping("/set-session") 438 | public String setSession(HttpSession session) { 439 | session.setAttribute("username", "John Doe"); 440 | return "Session set"; 441 | } 442 | 443 | @GetMapping("/get-session") 444 | public String getSession(HttpSession session) { 445 | return (String) session.getAttribute("username"); 446 | } 447 | } 448 | ``` 449 | 450 | ### 캐싱 451 | 데이터베이스 쿼리 결과나 API 응답을 Redis에 캐싱하여 응답 시간을 크게 줄일 수 있다. 452 | ```java 453 | @Cacheable(value = "userCache", key = "#userId") 454 | public User getUserById(String userId) { 455 | // 데이터베이스에서 사용자 정보를 가져오는 로직 456 | } 457 | ``` 458 | 459 | ### 실시간 랭킹 시스템 460 | 게임이나 리더보드에서 Sorted Set을 사용하여 실시간 랭킹을 구현할 수 있다. 461 | ```jsx 462 | > ZADD leaderboard 1000 "user:1" 463 | > ZADD leaderboard 2000 "user:2" 464 | > ZREVRANGE leaderboard 0 9 WITHSCORES // 상위 10명 조회 465 | ``` 466 | ### 메시지 큐 467 | List 자료구조를 사용하여 간단한 메시지 큐를 구현할 수 있다. 468 | ```jsx 469 | > LPUSH tasks "task:1" 470 | > RPOP tasks // 작업 처리 471 | ``` 472 | ### 실시간 분석 473 | HyperLogLog를 사용하여 대규모 데이터의 카디널리티를 추정할 수 있다. 예를 들어, 웹사이트의 일일 순 방문자 수를 추정할 수 있다. 474 | ```jsx 475 | > PFADD daily_visitors "user:1" "user:2" "user:3" 476 | > PFCOUNT daily_visitors 477 | ``` 478 | 479 | ### 속도 제한(Rate Limiting) 480 | 481 | API 요청의 속도를 제한하는 데 Redis를 사용할 수 있다. 482 | 483 | ```java 484 | @Service 485 | public class RateLimiter { 486 | private final StringRedisTemplate redisTemplate; 487 | 488 | public RateLimiter(StringRedisTemplate redisTemplate) { 489 | this.redisTemplate = redisTemplate; 490 | } 491 | 492 | public boolean allowRequest(String userId, int maxRequests, int timeWindowSeconds) { 493 | String key = "rate_limit:" + userId; 494 | long currentTime = System.currentTimeMillis() / 1000; 495 | 496 | List txResults = redisTemplate.execute(new SessionCallback>() { 497 | @Override 498 | public List execute(RedisOperations operations) throws DataAccessException { 499 | operations.multi(); 500 | operations.opsForZSet().add(key, String.valueOf(currentTime), currentTime); 501 | operations.opsForZSet().removeRangeByScore(key, 0, currentTime - timeWindowSeconds); 502 | operations.opsForZSet().size(key); 503 | return operations.exec(); 504 | } 505 | }); 506 | 507 | // 트랜잭션 결과 검증 508 | if (txResults == null || txResults.isEmpty()) { 509 | throw new RuntimeException("Redis transaction failed"); 510 | } 511 | 512 | // 마지막 결과(size 연산)가 Long 타입인지 확인 513 | if (!(txResults.get(txResults.size() - 1) instanceof Long)) { 514 | throw new RuntimeException("Unexpected result type from Redis transaction"); 515 | } 516 | 517 | Long requestCount = (Long) txResults.get(txResults.size() - 1); 518 | 519 | // 만료 시간 설정 (트랜잭션 외부에서 수행) 520 | redisTemplate.expire(key, timeWindowSeconds, TimeUnit.SECONDS); 521 | 522 | return requestCount <= maxRequests; 523 | } 524 | } 525 | 526 | // 사용 예 527 | @RestController 528 | public class ApiController { 529 | private final RateLimiter rateLimiter; 530 | 531 | public ApiController(RateLimiter rateLimiter) { 532 | this.rateLimiter = rateLimiter; 533 | } 534 | 535 | @GetMapping("/api/resource") 536 | public ResponseEntity getResource(@RequestHeader("User-Id") String userId) { 537 | try { 538 | if (!rateLimiter.allowRequest(userId, 10, 60)) { 539 | return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("Rate limit exceeded"); 540 | } 541 | // 실제 리소스 처리 로직 542 | return ResponseEntity.ok("Resource data"); 543 | } catch (Exception e) { 544 | // 로깅 추가 545 | return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred"); 546 | } 547 | } 548 | } 549 | ``` 550 | 551 | # Redis Quick Guide 프로젝트 설정 552 | 553 | 554 | 1. github.com에서 본인 계정의 빈 github project repository 생성 555 | 2. 로컬 clone 후 Springboot gradle 프로젝트 생성 (Spring-Redis) 556 | 3. root(Spring-Redis)에서 new > module...선택 557 | 4. Java project 선택 후 프로젝트 네임 입력, Gradle, Groovy 선택 후 Create 클릭 558 | 5. root의 src 폴더는 필요 없으므로 삭제 559 | 6. 이와 같은 형태로 여러 프로젝트 하위에 멀티 모듈 형태로 생성할 수 있으며, 연관관계를 따로 맺지 않고 개별 프로젝트로 사용함 560 | 561 | ![project생성](./image/redis-create.png) 562 | 563 | ## 프로젝트 구조 564 | 565 | 566 | 567 | 568 | > redis-sample : Spring startup시 간단한 메시지 출력 예제 569 | > 570 | > redis-crud : redis를 이용한 CRUD 활용 예제 571 | > 572 | > redis-pub/sub : message publish/subscribe 예제 573 | > 574 | 575 | root의 build.gradle은 아래와 같다. 하위 프로젝트들은 root의 설정에 의존성을 갖지만 root에는 소스가 없고 gradle 디펜던시만 맺도록 멀티 프로젝트를 구성한다. (다른 모듈관 의존 관계 없음) 576 | ```groovy 577 | plugins { 578 | id 'java' 579 | id 'org.springframework.boot' version '3.3.1' 580 | id 'io.spring.dependency-management' version '1.1.5' 581 | } 582 | 583 | group = 'com.villainscode' 584 | version = '0.0.1-SNAPSHOT' 585 | 586 | java { 587 | sourceCompatibility = '17' 588 | } 589 | 590 | configurations { 591 | compileOnly { 592 | extendsFrom annotationProcessor 593 | } 594 | } 595 | 596 | // 하위 프로젝트 모듈의 공통 플러그인 및 의존성 정의 597 | subprojects { 598 | apply plugin: 'java-library' 599 | apply plugin: 'idea' 600 | apply plugin: 'org.springframework.boot' 601 | apply plugin: 'io.spring.dependency-management' 602 | apply plugin: 'java' 603 | compileJava.options.encoding = 'UTF-8' 604 | sourceCompatibility = '17' 605 | 606 | task wrapper(type: Wrapper) { 607 | gradleVersion = '8.1.1' 608 | } 609 | 610 | repositories { 611 | mavenCentral() 612 | } 613 | 614 | dependencies { 615 | compileOnly 'org.projectlombok:lombok' 616 | developmentOnly 'org.springframework.boot:spring-boot-devtools' 617 | annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' 618 | annotationProcessor 'org.projectlombok:lombok' 619 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 620 | implementation 'org.springframework.boot:spring-boot-starter-data-redis' 621 | } 622 | 623 | 624 | tasks.named('test') { 625 | useJUnitPlatform() 626 | } 627 | } 628 | 629 | ``` 630 | root의 settings.gradle을 아래와 같다. 하위 프로젝트 생성 후 gradle refresh 하면 자동으로 추가되는 것을 확인할 수 있다. 631 | ```groovy 632 | rootProject.name = 'Spring-Redis' 633 | include 'redis-sample' 634 | include 'redis-crud' 635 | include 'redis-pub' 636 | include 'redis-sub' 637 | ``` 638 | 각 하위 프로젝트는 해당 프로젝트에서 필요한 모듈의 dependencies들을 각 build.gradle 에 추가해준 후 사용하면 된다. 639 | 640 | 기본 예제(redis-sample)는 특별한 라이브러리가 필요하지 않다. 641 | 하지만 redis-crud나 pub/sub 관련 모듈들은 spring-boot-starter-web 라이브러리가 필요하다. 각 모듈 하위의 build.gradle 파일을 참조하기 바란다. 642 | 643 | 또 sample이나 crud는 기본 포트인 8080으로 실행되지만 pub/sub은 따로 메시지를 주고 받아야 하므로 properties에서 server.port를 각각 8081, 8082로 설정했다. 644 | 645 | 각각의 모듈들을 실행한 뒤 API를 호출하는 .http 샘플은 아래와 같다. (.http 사용법에 대해서는 `intellij .http`로 구글링 하기 바란다 ) 646 | 647 | ```http request 648 | ### redis-sample Send message to testChannel 649 | POST http://localhost:8080/message/testChannel 650 | Content-Type: application/json 651 | 652 | { 653 | "message": "Hello, this is a test message." 654 | } 655 | 656 | ### redis-crud 657 | GET http://localhost:8080/api/v1/keys 658 | 659 | ### redis-crud 660 | GET http://localhost:8080/api/v1/getAll 661 | 662 | ### redis-pub Publish OrderQueue 663 | POST http://localhost:8081/publish 664 | Content-Type: application/json 665 | 666 | { 667 | "id": "order123", 668 | "userId": "user456", 669 | "productName": "Laptop", 670 | "price": 1200, 671 | "qty": 2 672 | } 673 | 674 | ``` 675 | -------------------------------------------------------------------------------- /redis-crud/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | 6 | group = 'com.villainscode' 7 | version = '0.0.1-SNAPSHOT' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation 'org.springframework.boot:spring-boot-starter-web' 15 | //implementation group: 'org.hibernate.validator', name: 'hibernate-validator', version: '7.0.5.Final' 16 | } 17 | 18 | test { 19 | useJUnitPlatform() 20 | } -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/RedisCrudApplication.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RedisCrudApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RedisCrudApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.config; 2 | 3 | import java.util.Arrays; 4 | import java.util.Objects; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.cache.annotation.CachingConfigurerSupport; 7 | import org.springframework.cache.annotation.EnableCaching; 8 | import org.springframework.cache.interceptor.KeyGenerator; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | // 환경 설정, 캐싱 활성화 13 | @Slf4j 14 | @Configuration 15 | @EnableCaching 16 | public class RedisConfig extends CachingConfigurerSupport { 17 | 18 | /** 19 | * 캐시 키 생성 정의 20 | * @return 21 | */ 22 | @Bean 23 | public KeyGenerator keyGenerator() { 24 | return (target, method, params) -> { 25 | StringBuilder key = new StringBuilder(); 26 | key.append(target.getClass().getName()).append("-"); 27 | key.append(method.getName()).append("-"); 28 | key.append(Arrays.toString(params)); 29 | 30 | return Objects.hash(key.toString()); 31 | }; 32 | } 33 | } -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/keygenerate/KeyGenerateService.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.keygenerate; 2 | 3 | import java.lang.reflect.Method; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.cache.interceptor.KeyGenerator; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author CodeVillains 10 | * @description : 11 | */ 12 | @Slf4j 13 | @Service 14 | public class KeyGenerateService { 15 | private final KeyGenerator keyGenerator; 16 | 17 | public KeyGenerateService(KeyGenerator keyGenerator) { 18 | this.keyGenerator = keyGenerator; 19 | } 20 | 21 | public void setKeyGenerator(Integer number, String value) throws NoSuchMethodException { 22 | // RedisConfig에서 정의한 KeyGenerator를 사용하여 키 생성 23 | Object generatedKey = keyGenerator.generate(this, getClass().getDeclaredMethod("setKeyGenerator", Integer.class, String.class), number, value); 24 | // 생성된 키를 Redis 또는 다른 용도로 사용 25 | log.info("Generated Redis Key : {}" + generatedKey); 26 | } 27 | 28 | public String generateKey(Integer number, String value) throws NoSuchMethodException { 29 | Method method = getClass().getDeclaredMethod("setKeyGenerator", Integer.class, String.class); 30 | Object generatedKey = keyGenerator.generate(this, method, number, value); 31 | log.info("# generatedKey = {}", generatedKey); 32 | return generatedKey.toString(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/message/MessageController.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.message; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.ResponseEntity; 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 | /** 12 | * @author CodeVillains 13 | * @description : test.http 14 | * POST http://localhost:8080/message/testChannel 15 | * Content-Type: application/json 16 | * 17 | * { 18 | * "message": "Hello, this is a test message." 19 | * } 20 | */ 21 | @Slf4j 22 | @RestController 23 | @RequestMapping("/message") 24 | public class MessageController { 25 | 26 | private final RedisPublisher redisPublisher; 27 | 28 | public MessageController(RedisPublisher redisPublisher) { 29 | this.redisPublisher = redisPublisher; 30 | } 31 | 32 | @PostMapping("/{channel}") 33 | public ResponseEntity sendMessage(@PathVariable String channel, @RequestBody String message) { 34 | log.info("channel = {}, {}", channel, message); 35 | redisPublisher.sendMessage(channel, message); 36 | return ResponseEntity.ok("message send to chnanel : " + channel + " and message : " + message); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/message/RedisPublisher.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.message; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.data.redis.core.StringRedisTemplate; 5 | import org.springframework.stereotype.Service; 6 | 7 | /** 8 | * @author CodeVillains 9 | * @description : 10 | */ 11 | @Slf4j 12 | @Service 13 | public class RedisPublisher { 14 | 15 | private final StringRedisTemplate stringRedisTemplate; 16 | 17 | public RedisPublisher(StringRedisTemplate stringRedisTemplate) { 18 | this.stringRedisTemplate = stringRedisTemplate; 19 | } 20 | 21 | public void sendMessage(String channel, String message) { 22 | log.info("# channel = {}, message = {}", channel, message); 23 | try { 24 | stringRedisTemplate.convertAndSend(channel, message); 25 | log.info("Message sent successfully to channel '{}'", channel); 26 | } catch (Exception e) { 27 | log.error("Failed to send message to channel '{}': {}", channel, e.getMessage()); 28 | e.printStackTrace(); // Handle or log the exception appropriately 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/message/RedisSubscriber.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.message; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.data.redis.connection.Message; 5 | import org.springframework.data.redis.connection.MessageListener; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author CodeVillains 10 | * @description : 11 | */ 12 | @Slf4j 13 | @Service 14 | public class RedisSubscriber implements MessageListener { 15 | 16 | @Override 17 | public void onMessage(Message message, byte[] pattern) { 18 | String receiveMessage = new String(message.getBody()); 19 | String channel = new String(message.getChannel()); 20 | 21 | log.info("Received message '{}' from channel '{}'", message, channel); 22 | if ("myChannel".equals(channel)) { 23 | log.info("Received message from 'myChannel': {}", message); 24 | // Add assertions or additional actions based on the received message 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/rediskey/RedisKeyController.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.rediskey; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.DeleteMapping; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.PutMapping; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RequestParam; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | /** 19 | * @author CodeVillains description : 20 | */ 21 | @Slf4j 22 | @RestController 23 | @RequestMapping("/api/v1") 24 | public class RedisKeyController { 25 | 26 | private final RedisKeyService redisKeyService; 27 | 28 | @Autowired 29 | public RedisKeyController(RedisKeyService redisKeyService) { 30 | this.redisKeyService = redisKeyService; 31 | } 32 | 33 | // GET http://localhost:8080/api/v1/keys 34 | @GetMapping("/keys") 35 | public Set getAllKeys() { 36 | log.info("# getAllKeys"); 37 | return redisKeyService.getAllKeys(); 38 | } 39 | 40 | @GetMapping("/getAll") 41 | public ResponseEntity> getAllKeysAndValues() { 42 | try { 43 | Map result = redisKeyService.getAllKeysAndValues(); 44 | return ResponseEntity.ok(result); 45 | } catch (Exception e) { 46 | log.error("An error occurred while fetching keys and values from Redis", e); 47 | // Return an error response with a 500 Internal Server Error status 48 | Map errorResponse = new HashMap<>(); 49 | errorResponse.put("error", "An error occurred while fetching keys and values from Redis"); 50 | return ResponseEntity.status(500).body(errorResponse); 51 | } 52 | } 53 | 54 | 55 | // POST http://localhost:8080/api/v1/save 56 | // Content-Type: application/x-www-form-urlencoded 57 | // 58 | //number=20231127&value=first 59 | @PostMapping("/save") 60 | public void saveData(@RequestParam Integer number, @RequestParam String value) { 61 | try { 62 | redisKeyService.save(number, value); 63 | } catch (NoSuchMethodException e) { 64 | e.printStackTrace(); 65 | } 66 | } 67 | 68 | 69 | // GET http://localhost:8080/api/v1/search?number=20231127&value=first 70 | @GetMapping("/search") 71 | public String searchData(@RequestParam Integer number, @RequestParam String value) { 72 | try { 73 | return redisKeyService.search(number, value); 74 | } catch (NoSuchMethodException e) { 75 | e.printStackTrace(); 76 | return "no search data error"; 77 | } 78 | } 79 | 80 | // PUT http://localhost:8080/api/v1/edit 81 | //Content-Type: application/json 82 | // 83 | //{ 84 | // "number": 123, 85 | // "newValue": "updatedValue" 86 | //} 87 | @PutMapping("/edit") 88 | public void editData(@RequestParam Integer number, @RequestParam String newValue) { 89 | try { 90 | redisKeyService.edit(number, newValue); 91 | } catch (NoSuchMethodException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | 96 | // DELETE http://localhost:8080/api/v1/delete?number=123&value=testValue 97 | @DeleteMapping("/delete") 98 | public void deleteData(@RequestParam Integer number, @RequestParam String value) { 99 | try { 100 | redisKeyService.delete(number, value); 101 | } catch (NoSuchMethodException e) { 102 | e.printStackTrace(); 103 | } 104 | 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /redis-crud/src/main/java/com/villainscode/redis/rediskey/RedisKeyService.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.rediskey; 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | import com.villainscode.redis.keygenerate.KeyGenerateService; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.cache.annotation.CacheEvict; 12 | import org.springframework.cache.annotation.Cacheable; 13 | import org.springframework.data.redis.core.RedisTemplate; 14 | import org.springframework.stereotype.Service; 15 | 16 | /** 17 | * @author CodeVillains 18 | * @description : 19 | */ 20 | @Slf4j 21 | @Service 22 | public class RedisKeyService { 23 | 24 | private final RedisTemplate redisTemplate; 25 | private KeyGenerateService keyGenerateService; 26 | 27 | public RedisKeyService(RedisTemplate redisTemplate, KeyGenerateService keyGenerateService) { 28 | this.redisTemplate = redisTemplate; 29 | this.keyGenerateService = keyGenerateService; 30 | } 31 | 32 | public Set getAllKeys() { 33 | return redisTemplate.keys("*"); 34 | } 35 | 36 | public Map getAllKeysAndValues() { 37 | Set keys = redisTemplate.keys("*"); 38 | Map keyValueMap = new HashMap<>(); 39 | if (keys != null) { 40 | for (String key : keys) { 41 | try { 42 | log.debug("Processing key: {}", key); 43 | String type = redisTemplate.type(key).code(); 44 | Object value = null; 45 | switch (type) { 46 | case "string": 47 | value = redisTemplate.opsForValue().get(key); 48 | break; 49 | case "list": 50 | value = redisTemplate.opsForList().range(key, 0, -1); 51 | break; 52 | case "set": 53 | value = redisTemplate.opsForSet().members(key); 54 | break; 55 | case "zset": 56 | value = redisTemplate.opsForZSet().range(key, 0, -1); 57 | break; 58 | case "hash": 59 | value = redisTemplate.opsForHash().entries(key); 60 | break; 61 | default: 62 | value = "Unsupported data type"; 63 | break; 64 | } 65 | keyValueMap.put(key, value); 66 | } catch (Exception e) { 67 | log.error("Error processing key: {}", key, e); 68 | } 69 | } 70 | } 71 | return keyValueMap; 72 | } 73 | 74 | private Map getValuesByKeys(Set keys) { 75 | Map keyValueMap = new HashMap<>(); 76 | if (keys != null) { 77 | for (String key : keys) { 78 | String value = redisTemplate.opsForValue().get(key); 79 | keyValueMap.put(key, value); 80 | } 81 | } 82 | return keyValueMap; 83 | } 84 | 85 | @CacheEvict(value = "cacheKey", key = "#number + #value") 86 | public void save(Integer number, String value) throws NoSuchMethodException { 87 | String key = keyGenerateService.generateKey(number, value); 88 | redisTemplate.opsForValue().set(key, "Example Data for " + key); 89 | log.info("# Stored data in Redis with key : {}", key); 90 | } 91 | 92 | @Cacheable(value = "cacheKey", key = "#number + #value") 93 | public String search(Integer number, String value) throws NoSuchMethodException { 94 | String key = keyGenerateService.generateKey(number, value); 95 | String storedData = redisTemplate.opsForValue().get(key); 96 | log.info("# Retrieved data from Redis with key : {}", key); 97 | return storedData; 98 | } 99 | 100 | @CacheEvict(value = "cacheKey", key = "#number + #value") 101 | public void edit(Integer number, String newValue) throws NoSuchMethodException { 102 | String key = keyGenerateService.generateKey(number, newValue); 103 | // edit 104 | redisTemplate.opsForValue().set(key, newValue); 105 | log.info("# Edited data in Redis with key : {}", key); 106 | } 107 | 108 | @CacheEvict(value = "cacheKey", key = "#number + #value") 109 | public void delete(Integer number, String value) throws NoSuchMethodException { 110 | String key = keyGenerateService.generateKey(number, value); 111 | // delete 112 | Boolean deleted = redisTemplate.delete(key); 113 | log.info("# Deleted data in Redis with key : {}", key); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /redis-crud/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | 3 | spring.data.redis.url=redis://localhost:6379 -------------------------------------------------------------------------------- /redis-crud/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %d{yyyy-MM-dd HH:mm:ss} - %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /redis-pub/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | 6 | group = 'com.villainscode' 7 | version = '0.0.1-SNAPSHOT' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation 'org.springframework.boot:spring-boot-starter-web' 15 | //implementation group: 'org.hibernate.validator', name: 'hibernate-validator', version: '7.0.5.Final' 16 | } 17 | 18 | test { 19 | useJUnitPlatform() 20 | } -------------------------------------------------------------------------------- /redis-pub/src/main/java/com/villainscode/redis/RedisPubApplication.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author CodeVillains 8 | * @description : 9 | */ 10 | @SpringBootApplication 11 | public class RedisPubApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(RedisPubApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /redis-pub/src/main/java/com/villainscode/redis/config/RedisConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; 8 | 9 | @Configuration 10 | public class RedisConfiguration { 11 | 12 | @Bean(name = "publisherRedisTemplate") 13 | public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { 14 | 15 | RedisTemplate template = new RedisTemplate<>(); 16 | template.setConnectionFactory(connectionFactory); 17 | template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); 18 | return template; 19 | } 20 | } -------------------------------------------------------------------------------- /redis-pub/src/main/java/com/villainscode/redis/model/OrderQueue.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.model; 2 | 3 | import java.io.Serializable; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Data 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | @Builder 13 | public class OrderQueue implements Serializable { 14 | 15 | private String id; 16 | private String userId; 17 | private String productName; 18 | private int price; 19 | private int qty; 20 | } -------------------------------------------------------------------------------- /redis-pub/src/main/java/com/villainscode/redis/publisher/OrderService.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.publisher; 2 | 3 | import com.villainscode.redis.model.OrderQueue; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.data.redis.core.RedisTemplate; 8 | import org.springframework.data.redis.listener.ChannelTopic; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * @author CodeVillains 13 | * @description : 14 | */ 15 | @Slf4j 16 | @Service 17 | public class OrderService { 18 | 19 | @Autowired 20 | @Qualifier("publisherRedisTemplate") 21 | private RedisTemplate redisTemplate; 22 | 23 | @Autowired 24 | private ChannelTopic channelTopic; 25 | 26 | public Long publish(OrderQueue orderQueue) { 27 | log.info("# publish order queue = {}", orderQueue); 28 | return redisTemplate.convertAndSend(channelTopic.getTopic(), orderQueue); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /redis-pub/src/main/java/com/villainscode/redis/publisher/PublisherController.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.publisher; 2 | 3 | 4 | import com.villainscode.redis.model.OrderQueue; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * @author CodeVillains 11 | * @description : 12 | */ 13 | @RestController 14 | public class PublisherController { 15 | private final OrderService orderService; 16 | 17 | public PublisherController(OrderService orderService) { 18 | this.orderService = orderService; 19 | } 20 | 21 | @PostMapping("/publish") 22 | public String publish(@RequestBody OrderQueue orderQueue) { 23 | orderService.publish(orderQueue); 24 | return "Success"; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /redis-pub/src/main/java/com/villainscode/redis/publisher/RedisPublisher.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.publisher; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.data.redis.listener.ChannelTopic; 8 | 9 | /** 10 | * @author CodeVillains 11 | * @description : 12 | */ 13 | @Slf4j 14 | @Configuration 15 | public class RedisPublisher { 16 | @Value("${redis.publisher.topic}") 17 | private String topic; 18 | 19 | @Bean 20 | public ChannelTopic topic() { 21 | log.info("# topic = {}", topic); 22 | return new ChannelTopic(topic); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /redis-pub/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | 3 | spring.data.redis.url=redis://localhost:6379 4 | 5 | redis.publisher.topic=order-q 6 | stream.key=order-id 7 | -------------------------------------------------------------------------------- /redis-sample/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group = 'com.villainscode.redis' 6 | version = '0.0.1-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | 14 | } 15 | 16 | test { 17 | useJUnitPlatform() 18 | } -------------------------------------------------------------------------------- /redis-sample/src/main/java/com/villainscode/redis/SpringRedisApplication.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis; 2 | 3 | 4 | import message.Receiver; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.data.redis.connection.RedisConnectionFactory; 12 | import org.springframework.data.redis.core.StringRedisTemplate; 13 | import org.springframework.data.redis.listener.PatternTopic; 14 | import org.springframework.data.redis.listener.RedisMessageListenerContainer; 15 | import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; 16 | 17 | @SpringBootApplication 18 | public class SpringRedisApplication { 19 | 20 | private static final Logger LOGGER = LoggerFactory.getLogger(SpringRedisApplication.class); 21 | 22 | @Bean 23 | RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { 24 | RedisMessageListenerContainer container = new RedisMessageListenerContainer(); 25 | container.setConnectionFactory(connectionFactory); 26 | container.addMessageListener(listenerAdapter, new PatternTopic("chat")); 27 | return container; 28 | } 29 | 30 | @Bean 31 | MessageListenerAdapter listenerAdapter(Receiver receiver) { 32 | return new MessageListenerAdapter(receiver, "receiveMessage"); 33 | } 34 | 35 | @Bean 36 | Receiver receiver() { 37 | return new Receiver(); 38 | } 39 | 40 | @Bean 41 | StringRedisTemplate template(RedisConnectionFactory connectionFactory) { 42 | return new StringRedisTemplate(connectionFactory); 43 | } 44 | public static void main(String[] args) throws InterruptedException { 45 | ApplicationContext ctx = SpringApplication.run(SpringRedisApplication.class, args); 46 | StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); 47 | Receiver receiver = ctx.getBean(Receiver.class); 48 | 49 | while (receiver.getCount() == 0) { 50 | LOGGER.info("Waiting for messages..."); 51 | template.convertAndSend("chat", "Hello from redis!"); 52 | Thread.sleep(500L); 53 | } 54 | System.exit(0); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /redis-sample/src/main/java/message/Receiver.java: -------------------------------------------------------------------------------- 1 | package message; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | /** 8 | * @author CodeVillains description : 9 | */ 10 | public class Receiver { 11 | private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class); 12 | 13 | private AtomicInteger count = new AtomicInteger(); 14 | 15 | public void receiveMessage(String message) { 16 | LOGGER.info("Received <" + message + ">"); 17 | count.incrementAndGet(); 18 | } 19 | 20 | public int getCount() { 21 | return count.get(); 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /redis-sample/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %d{yyyy-MM-dd HH:mm:ss} - %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /redis-sub/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | 6 | group = 'com.villainscode' 7 | version = '0.0.1-SNAPSHOT' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation 'org.springframework.boot:spring-boot-starter-web' 15 | //implementation group: 'org.hibernate.validator', name: 'hibernate-validator', version: '7.0.5.Final' 16 | } 17 | 18 | test { 19 | useJUnitPlatform() 20 | } -------------------------------------------------------------------------------- /redis-sub/src/main/java/com/villainscode/redis/RedisSubApplication.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author CodeVillains 8 | * @description : 9 | */ 10 | @SpringBootApplication 11 | public class RedisSubApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(RedisSubApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /redis-sub/src/main/java/com/villainscode/redis/config/RedisConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.redis.connection.RedisConnectionFactory; 7 | import org.springframework.data.redis.core.RedisTemplate; 8 | import org.springframework.data.redis.listener.ChannelTopic; 9 | import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; 10 | 11 | /** 12 | * @author CodeVillains 13 | * @description : 14 | */ 15 | @Configuration 16 | public class RedisConfiguration { 17 | 18 | @Value(value = "${redis.publisher.topic:order-q}") 19 | private String topic; 20 | 21 | @Bean 22 | public ChannelTopic topic() { 23 | return new ChannelTopic(topic); 24 | } 25 | 26 | @Bean(name = "subscriberRedisTemplate") 27 | public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { 28 | RedisTemplate template = new RedisTemplate<>(); 29 | template.setConnectionFactory(redisConnectionFactory); 30 | template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); 31 | return template; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /redis-sub/src/main/java/com/villainscode/redis/config/SubscriberConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.MessageListener; 6 | import org.springframework.data.redis.connection.RedisConnectionFactory; 7 | import org.springframework.data.redis.listener.ChannelTopic; 8 | import org.springframework.data.redis.listener.RedisMessageListenerContainer; 9 | 10 | /** 11 | * @author CodeVillains 12 | * @description : 13 | */ 14 | @Configuration 15 | public class SubscriberConfiguration { 16 | 17 | private final MessageListener messageListener; 18 | private final RedisConnectionFactory redisConnectionFactory; 19 | 20 | public SubscriberConfiguration(MessageListener messageListener, RedisConnectionFactory redisConnectionFactory) { 21 | this.messageListener = messageListener; 22 | this.redisConnectionFactory = redisConnectionFactory; 23 | } 24 | 25 | @Bean 26 | public RedisMessageListenerContainer redisMessageListenerContainer(ChannelTopic topic) { 27 | RedisMessageListenerContainer container = new RedisMessageListenerContainer(); 28 | container.setConnectionFactory(redisConnectionFactory); 29 | container.addMessageListener(messageListener, topic); 30 | return container; 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /redis-sub/src/main/java/com/villainscode/redis/subscriber/OrderDTO.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.subscriber; 2 | 3 | import java.io.Serializable; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Data 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | @Builder 13 | public class OrderDTO implements Serializable { 14 | 15 | 16 | private String id; 17 | private String userId; 18 | private String productName; 19 | private int price; 20 | private int qty; 21 | } -------------------------------------------------------------------------------- /redis-sub/src/main/java/com/villainscode/redis/subscriber/SubscriberEventListener.java: -------------------------------------------------------------------------------- 1 | package com.villainscode.redis.subscriber; 2 | 3 | import com.fasterxml.jackson.core.exc.StreamReadException; 4 | import com.fasterxml.jackson.databind.DatabindException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import java.io.IOException; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Qualifier; 10 | import org.springframework.data.redis.connection.Message; 11 | import org.springframework.data.redis.connection.MessageListener; 12 | import org.springframework.data.redis.core.RedisTemplate; 13 | import org.springframework.stereotype.Service; 14 | 15 | /** 16 | * @author CodeVillains 17 | * @description : 18 | */ 19 | @Slf4j 20 | @Service 21 | public class SubscriberEventListener implements MessageListener { 22 | 23 | @Autowired 24 | private ObjectMapper objectMapper; 25 | 26 | @Autowired 27 | @Qualifier("subscriberRedisTemplate") 28 | private RedisTemplate redisTemplate; 29 | 30 | @Override 31 | public void onMessage(Message message, byte[] pattern) { 32 | try { 33 | log.info("# new message received = {}", message); 34 | OrderDTO orderDTO = objectMapper.readValue(message.getBody(), OrderDTO.class); 35 | } catch (IOException e) { 36 | log.error("# Subscriber Event Error = {}", message); 37 | throw new RuntimeException(e); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /redis-sub/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8082 2 | 3 | spring.data.redis.url=redis://localhost:6379 -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Spring-Redis' 2 | include 'redis-sample' 3 | include 'redis-crud' 4 | include 'redis-pub' 5 | include 'redis-sub' 6 | 7 | --------------------------------------------------------------------------------