├── .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 |
4 |
5 |
6 |
7 |
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