├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── redis │ │ └── cluster │ │ ├── RedisClusterApplication.java │ │ ├── common │ │ └── CacheKey.java │ │ ├── config │ │ └── RedisCacheConfig.java │ │ ├── controller │ │ ├── PubSubController.java │ │ └── RedisController.java │ │ ├── entity │ │ ├── User.java │ │ └── redis │ │ │ └── Student.java │ │ ├── pubsub │ │ ├── RedisPublisher.java │ │ ├── RedisSubscriber.java │ │ └── RoomMessage.java │ │ └── repo │ │ ├── UserJpaRepo.java │ │ └── redis │ │ └── StudentRedisRepo.java └── resources │ └── application.yml └── test ├── java └── com │ └── redis │ └── cluster │ ├── ReactiveRedisClusterTest.java │ ├── RedisClusterTest.java │ └── controller │ └── RedisControllerTest.java └── resources └── logback-test.xml /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | /build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | 6 | ### STS ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | /out/ 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | 29 | ### VS Code ### 30 | .vscode/ 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Java_8](https://img.shields.io/badge/java-v1.8-red?logo=java) 2 | ![Spring_Boot](https://img.shields.io/badge/Spring_Boot-2.1.4-green.svg?logo=spring) 3 | ![Spring_Data_Redis](https://img.shields.io/badge/Spring_Data_Redis-2.1.4-green.svg?logo=redis) 4 | ![GitHub stars](https://img.shields.io/github/stars/codej99/SpringRedisCluster?style=social) 5 | 6 | # Redis(in-memory data structure store) 알아보기 7 | 8 | ### 0. 개요 9 | - Redis5.x 버전 설치 및 사용 방법 그리고 Spring Data Redis와의 연동방법을 실습합니다. 10 | - daddyprogrammer.org에서 연재 및 소스 Github 등록 11 | - https://daddyprogrammer.org/post/series/redis-in-memory-data-structure-store/ 12 | 13 | ### 1. 실습 환경 14 | - Redis 5.x 15 | - Java 8~11 16 | - SpringBoot 2.x 17 | - Spring-Data-Redis 18 | - JPA, H2 19 | - Intellij Community 20 | 21 | ### 2. 목차 22 | - Redis Install 23 | - Document 24 | - https://daddyprogrammer.org/post/1229/redis-single-instance/ 25 | - Redis – cluster 26 | - Document 27 | - https://daddyprogrammer.org/post/1601/redis-cluster/ 28 | - Redis – SpringBoot2 redis cluster : strings, lists, hashs, sets, sortedsets, geo, hyperloglog 29 | - Document 30 | - https://daddyprogrammer.org/post/2241/redis-spring-data-redis-cluster-structure-comands/ 31 | - Git 32 | - https://github.com/codej99/SpringRedisCluster/tree/feature/rediscluster 33 | - Redis – Spring-data-redis : @Cacheable, @CachePut, @CacheEvict, @RedisHash 34 | - Document 35 | - https://daddyprogrammer.org/post/3217/redis-springboot2-spring-data-redis-cacheable-cacheput-cacheevict/ 36 | - Git 37 | - https://github.com/codej99/SpringRedisCluster/tree/feature/redisannotation 38 | - Redis – spring-data-redis : 발행/구독(pub/sub) 모델의 구현 39 | - Document 40 | - https://daddyprogrammer.org/post/3688/redis-spring-data-redis-publish-subscribe/ 41 | - Git 42 | - https://github.com/codej99/SpringRedisCluster/tree/feature/pubsub 43 | - Redis – reactive redis 44 | - Document 45 | - https://daddyprogrammer.org/post/4056/reactive-redis/ 46 | - Git 47 | - https://github.com/codej99/SpringRedisCluster/tree/feature/reactive 48 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.4.RELEASE' 3 | id 'java' 4 | } 5 | 6 | apply plugin: 'io.spring.dependency-management' 7 | 8 | group = 'com.rest' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '1.8' 11 | 12 | configurations { 13 | compileOnly { 14 | extendsFrom annotationProcessor 15 | } 16 | } 17 | 18 | repositories { 19 | mavenCentral() 20 | } 21 | 22 | dependencies { 23 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 24 | implementation 'org.springframework.boot:spring-boot-starter-freemarker' 25 | implementation 'org.springframework.boot:spring-boot-starter-web' 26 | implementation 'org.springframework.boot:spring-boot-starter-data-redis' 27 | implementation 'org.springframework.boot:spring-boot-starter-cache' 28 | implementation 'org.springframework.boot:spring-boot-starter-data-redis-reactive' 29 | implementation 'com.google.code.gson:gson' 30 | implementation 'com.h2database:h2' 31 | compileOnly 'org.projectlombok:lombok' 32 | runtimeOnly 'mysql:mysql-connector-java' 33 | annotationProcessor 'org.projectlombok:lombok' 34 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 35 | testImplementation 'io.projectreactor:reactor-test:3.1.0.RELEASE' 36 | testCompileOnly 'org.projectlombok:lombok' 37 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codej99/SpringRedisCluster/c4169162cf381d44f8c7df516d411eb7e3c7bb74/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue May 07 23:44:13 KST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'cluster' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/RedisClusterApplication.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RedisClusterApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RedisClusterApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/common/CacheKey.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.common; 2 | 3 | public class CacheKey { 4 | 5 | private CacheKey() { 6 | } 7 | 8 | public static final int DEFAULT_EXPIRE_SEC = 60; 9 | 10 | public static final String USER = "user"; 11 | public static final int USER_EXPIRE_SEC = 180; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/config/RedisCacheConfig.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.config; 2 | 3 | import com.redis.cluster.common.CacheKey; 4 | import org.springframework.cache.annotation.EnableCaching; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.data.redis.cache.CacheKeyPrefix; 8 | import org.springframework.data.redis.cache.RedisCacheConfiguration; 9 | import org.springframework.data.redis.cache.RedisCacheManager; 10 | import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; 11 | import org.springframework.data.redis.connection.RedisConnectionFactory; 12 | import org.springframework.data.redis.core.ReactiveRedisTemplate; 13 | import org.springframework.data.redis.core.RedisTemplate; 14 | import org.springframework.data.redis.listener.RedisMessageListenerContainer; 15 | import org.springframework.data.redis.serializer.*; 16 | 17 | import java.time.Duration; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | @Configuration 22 | @EnableCaching 23 | public class RedisCacheConfig { 24 | 25 | @Bean(name = "cacheManager") 26 | public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { 27 | 28 | RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig() 29 | .disableCachingNullValues() 30 | .entryTtl(Duration.ofSeconds(CacheKey.DEFAULT_EXPIRE_SEC)) 31 | .computePrefixWith(CacheKeyPrefix.simple()) 32 | .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())); 33 | 34 | Map cacheConfigurations = new HashMap<>(); 35 | // User 36 | cacheConfigurations.put(CacheKey.USER, RedisCacheConfiguration.defaultCacheConfig() 37 | .entryTtl(Duration.ofSeconds(CacheKey.USER_EXPIRE_SEC))); 38 | 39 | return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration) 40 | .withInitialCacheConfigurations(cacheConfigurations).build(); 41 | } 42 | 43 | @Bean 44 | public RedisMessageListenerContainer RedisMessageListener(RedisConnectionFactory connectionFactory) { 45 | RedisMessageListenerContainer container = new RedisMessageListenerContainer(); 46 | container.setConnectionFactory(connectionFactory); 47 | return container; 48 | } 49 | 50 | @Bean 51 | public RedisTemplate redisTemplateForObject(RedisConnectionFactory connectionFactory) { 52 | RedisTemplate redisTemplate = new RedisTemplate<>(); 53 | redisTemplate.setConnectionFactory(connectionFactory); 54 | redisTemplate.setKeySerializer(new StringRedisSerializer()); 55 | redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(String.class)); 56 | return redisTemplate; 57 | } 58 | 59 | @Bean 60 | public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory) { 61 | RedisSerializer serializer = new StringRedisSerializer(); 62 | Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(String.class); 63 | RedisSerializationContext serializationContext = RedisSerializationContext 64 | .newSerializationContext() 65 | .key(serializer) 66 | .value(jackson2JsonRedisSerializer) 67 | .hashKey(serializer) 68 | .hashValue(jackson2JsonRedisSerializer) 69 | .build(); 70 | 71 | return new ReactiveRedisTemplate<>(connectionFactory, serializationContext); 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/controller/PubSubController.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.controller; 2 | 3 | import com.redis.cluster.pubsub.RedisPublisher; 4 | import com.redis.cluster.pubsub.RedisSubscriber; 5 | import com.redis.cluster.pubsub.RoomMessage; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.data.redis.listener.ChannelTopic; 8 | import org.springframework.data.redis.listener.RedisMessageListenerContainer; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import javax.annotation.PostConstruct; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | import java.util.Set; 15 | 16 | @RequiredArgsConstructor 17 | @RequestMapping("/pubsub") 18 | @RestController 19 | public class PubSubController { 20 | // topic에 발행되는 액션을 처리할 Listner 21 | private final RedisMessageListenerContainer redisMessageListener; 22 | // 발행자 23 | private final RedisPublisher redisPublisher; 24 | // 구독자 25 | private final RedisSubscriber redisSubscriber; 26 | // 특정 topic에 메시지를 발송할 수 있도록 topic정보를 Map에 저장 27 | private Map channels; 28 | 29 | @PostConstruct 30 | public void init() { 31 | // 실행될때 topic정보를 담을 Map을 초기화 32 | channels = new HashMap<>(); 33 | } 34 | 35 | // 유효한 Topic 리스트 반환 36 | @GetMapping("/room") 37 | public Set findAllRoom() { 38 | return channels.keySet(); 39 | } 40 | 41 | // Topic 생성하여 Listener에 등록후 Topic Map에 저장 42 | @PutMapping("/room/{roomId}") 43 | public void createRoom(@PathVariable String roomId) { 44 | ChannelTopic channel = new ChannelTopic(roomId); 45 | redisMessageListener.addMessageListener(redisSubscriber, channel); 46 | channels.put(roomId, channel); 47 | } 48 | 49 | // 특정 Topic에 메시지 발송 50 | @PostMapping("/room/{roomId}") 51 | public void pushMessage(@PathVariable String roomId, @RequestParam String name, @RequestParam String message) { 52 | ChannelTopic channel = channels.get(roomId); 53 | redisPublisher.publish(channel, RoomMessage.builder().name(name).roomId(roomId).message(message).build()); 54 | } 55 | 56 | // 특정 Topic 삭제 후 Listener 해제 57 | @DeleteMapping("/room/{roomId}") 58 | public void deleteRoom(@PathVariable String roomId) { 59 | ChannelTopic channel = channels.get(roomId); 60 | redisMessageListener.removeMessageListener(redisSubscriber, channel); 61 | channels.remove(roomId); 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/controller/RedisController.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.controller; 2 | 3 | import com.redis.cluster.common.CacheKey; 4 | import com.redis.cluster.entity.User; 5 | import com.redis.cluster.repo.UserJpaRepo; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.cache.annotation.CacheEvict; 8 | import org.springframework.cache.annotation.CachePut; 9 | import org.springframework.cache.annotation.Cacheable; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | @RequiredArgsConstructor 13 | @RequestMapping("/redis") 14 | @RestController 15 | public class RedisController { 16 | 17 | private final UserJpaRepo userJpaRepo; 18 | 19 | @Cacheable(value = CacheKey.USER, key = "#msrl", unless = "#result == null") 20 | @GetMapping("/user/{msrl}") 21 | public User findOne(@PathVariable long msrl) { 22 | return userJpaRepo.findById(msrl).orElse(null); 23 | } 24 | 25 | @PostMapping("/user") 26 | public User postUser(@RequestBody User user) { 27 | return userJpaRepo.save(user); 28 | } 29 | 30 | @CachePut(value = CacheKey.USER, key = "#user.msrl") 31 | @PutMapping("/user") 32 | public User putUser(@RequestBody User user) { 33 | return userJpaRepo.save(user); 34 | } 35 | 36 | @CacheEvict(value = CacheKey.USER, key = "#msrl") 37 | @DeleteMapping("/user/{msrl}") 38 | public boolean deleteUser(@PathVariable long msrl) { 39 | userJpaRepo.deleteById(msrl); 40 | return true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | 9 | import javax.persistence.*; 10 | import java.io.Serializable; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Entity // jpa entity임을 알립니다. 15 | @Builder // builder를 사용할수 있게 합니다. 16 | @Getter // user 필드값의 getter를 자동으로 생성합니다. 17 | @NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다. 18 | @AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다. 19 | @Table(name = "user") // 'user' 테이블과 매핑됨을 명시 20 | public class User implements Serializable { 21 | @Id // pk 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private long msrl; 24 | @Column(nullable = false, unique = true, length = 50) 25 | private String uid; 26 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 27 | @Column(length = 100) 28 | private String password; 29 | @Column(nullable = false, length = 100) 30 | private String name; 31 | 32 | @ElementCollection(fetch = FetchType.EAGER) 33 | @Builder.Default 34 | private List roles = new ArrayList<>(); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/entity/redis/Student.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.entity.redis; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | import org.springframework.data.annotation.Id; 6 | import org.springframework.data.redis.core.RedisHash; 7 | 8 | @Getter 9 | @Builder 10 | @RedisHash("student") 11 | public class Student { 12 | @Id 13 | private long studentId; 14 | private String name; 15 | 16 | public void update(String name) { 17 | this.name = name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/pubsub/RedisPublisher.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.pubsub; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.data.redis.core.RedisTemplate; 5 | import org.springframework.data.redis.listener.ChannelTopic; 6 | import org.springframework.stereotype.Service; 7 | 8 | @RequiredArgsConstructor 9 | @Service 10 | public class RedisPublisher { 11 | 12 | private final RedisTemplate redisTemplate; 13 | 14 | public void publish(ChannelTopic topic, RoomMessage message) { 15 | redisTemplate.convertAndSend(topic.getTopic(), message); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/pubsub/RedisSubscriber.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.pubsub; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.data.redis.connection.Message; 7 | import org.springframework.data.redis.connection.MessageListener; 8 | import org.springframework.data.redis.core.RedisTemplate; 9 | import org.springframework.stereotype.Service; 10 | 11 | @Slf4j 12 | @RequiredArgsConstructor 13 | @Service 14 | public class RedisSubscriber implements MessageListener { 15 | 16 | private final ObjectMapper objectMapper; 17 | private final RedisTemplate redisTemplate; 18 | 19 | @Override 20 | public void onMessage(Message message, byte[] pattern) { 21 | try { 22 | String body = (String) redisTemplate.getStringSerializer().deserialize(message.getBody()); 23 | RoomMessage roomMessage = objectMapper.readValue(body, RoomMessage.class); 24 | log.info("Room - Message : {}", roomMessage.toString()); 25 | } catch (Exception e) { 26 | log.error(e.getMessage()); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/pubsub/RoomMessage.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.pubsub; 2 | 3 | import lombok.*; 4 | 5 | import java.io.Serializable; 6 | 7 | @Getter 8 | @Builder 9 | @NoArgsConstructor 10 | @AllArgsConstructor 11 | @ToString 12 | public class RoomMessage implements Serializable { 13 | private static final long serialVersionUID = 2082503192322391880L; 14 | private String roomId; 15 | private String name; 16 | private String message; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/repo/UserJpaRepo.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.repo; 2 | 3 | import com.redis.cluster.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserJpaRepo extends JpaRepository { 9 | 10 | Optional findByUid(String email); 11 | } -------------------------------------------------------------------------------- /src/main/java/com/redis/cluster/repo/redis/StudentRedisRepo.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.repo.redis; 2 | 3 | import com.redis.cluster.entity.redis.Student; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | public interface StudentRedisRepo extends CrudRepository { 7 | } 8 | 9 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8081 3 | 4 | logging: 5 | level: 6 | root: info 7 | com.rest.api: debug 8 | 9 | spring: 10 | datasource: 11 | url: jdbc:h2:tcp://localhost/~/test 12 | driver-class-name: org.h2.Driver 13 | username: sa 14 | jpa: 15 | database-platform: org.hibernate.dialect.H2Dialect 16 | properties.hibernate: 17 | hbm2ddl.auto: update 18 | format_sql: true 19 | showSql: true 20 | generate-ddl: true 21 | redis: 22 | cluster: 23 | nodes: 24 | - 15.164.98.87:6300 25 | - 15.164.98.87:6301 26 | - 15.164.98.87:6302 27 | - 15.164.98.87:6400 28 | - 15.164.98.87:6401 29 | - 15.164.98.87:6402 30 | max-redirects: 3 31 | password: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 32 | -------------------------------------------------------------------------------- /src/test/java/com/redis/cluster/ReactiveRedisClusterTest.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.data.geo.Point; 9 | import org.springframework.data.redis.connection.DataType; 10 | import org.springframework.data.redis.core.*; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import reactor.core.publisher.Mono; 13 | import reactor.test.StepVerifier; 14 | 15 | import java.util.*; 16 | 17 | @Slf4j 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest 20 | public class ReactiveRedisClusterTest { 21 | 22 | @Autowired 23 | private RedisTemplate redisTemplate; 24 | 25 | @Autowired 26 | private ReactiveRedisTemplate reactiveRedisTemplate; 27 | 28 | /** 29 | * 문자 데이터 구조 처리 30 | */ 31 | @Test 32 | public void opsValue() { 33 | ReactiveValueOperations valueOps = reactiveRedisTemplate.opsForValue(); 34 | Set cacheKeys = new HashSet<>(); 35 | // async process 36 | log.info("Step-1"); 37 | for (int i = 0; i < 5000; i++) { 38 | String key = "value_" + i; 39 | cacheKeys.add(key); 40 | valueOps.set(key, String.valueOf(i)); 41 | } 42 | log.info("Step-2"); 43 | Mono> values = valueOps.multiGet(cacheKeys); 44 | log.info("Step-3"); 45 | StepVerifier.create(values) 46 | .expectNextMatches(x -> x.size() == 5000).verifyComplete(); 47 | log.info("Step-4"); 48 | } 49 | 50 | /** 51 | * List 데이터 구조 처리 - 순서 있음. value 중복 허용 52 | */ 53 | @Test 54 | public void opsList() { 55 | ReactiveListOperations listOps = reactiveRedisTemplate.opsForList(); 56 | String cacheKey = "valueList"; 57 | 58 | // previous key delete - sync process 59 | redisTemplate.delete(cacheKey); 60 | 61 | // async process 62 | Mono results = listOps.leftPushAll(cacheKey, "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); 63 | StepVerifier.create(results).expectNext(10L).verifyComplete(); 64 | StepVerifier.create(reactiveRedisTemplate.type(cacheKey)).expectNext(DataType.LIST).verifyComplete(); 65 | StepVerifier.create(listOps.size(cacheKey)).expectNext(10L).verifyComplete(); 66 | StepVerifier.create(listOps.rightPop(cacheKey)).expectNext("0").verifyComplete(); 67 | StepVerifier.create(listOps.leftPop(cacheKey)).expectNext("9").verifyComplete(); 68 | } 69 | 70 | /** 71 | * Hash 데이터 구조 처리 - 순서 없음. key 중복허용 안함, value 중복 허용 72 | */ 73 | @Test 74 | public void opsHash() { 75 | ReactiveHashOperations hashOps = reactiveRedisTemplate.opsForHash(); 76 | String cacheKey = "valueHash"; 77 | Map setDatas = new HashMap<>(); 78 | for (int i = 0; i < 10; i++) { 79 | setDatas.put("key_" + i, "value_" + i); 80 | } 81 | 82 | // previous key delete - sync 83 | redisTemplate.delete(cacheKey); 84 | 85 | // async process 86 | StepVerifier.create(hashOps.putAll(cacheKey, setDatas)).expectNext(true).verifyComplete(); 87 | StepVerifier.create(reactiveRedisTemplate.type(cacheKey)).expectNext(DataType.HASH).verifyComplete(); 88 | StepVerifier.create(hashOps.size(cacheKey)).expectNext(10L).verifyComplete(); 89 | StepVerifier.create(hashOps.get(cacheKey, "key_5")).expectNext("value_5").verifyComplete(); 90 | StepVerifier.create(hashOps.remove(cacheKey, "key_5")).expectNext(1L).verifyComplete(); 91 | } 92 | 93 | /** 94 | * Set 데이터 구조 처리 - 순서 없음, value 중복 허용 안함 95 | */ 96 | @Test 97 | public void opsSet() { 98 | ReactiveSetOperations setOps = reactiveRedisTemplate.opsForSet(); 99 | String cacheKey = "valueSet"; 100 | 101 | // previous key delete - sync process 102 | redisTemplate.delete(cacheKey); 103 | 104 | // async process 105 | StepVerifier.create(setOps.add(cacheKey, "0", "1", "2", "3", "4", "5", "6", "7", "8", "9")).expectNext(10L).verifyComplete(); 106 | StepVerifier.create(reactiveRedisTemplate.type(cacheKey)).expectNext(DataType.SET).verifyComplete(); 107 | StepVerifier.create(setOps.size(cacheKey)).expectNext(10L).verifyComplete(); 108 | StepVerifier.create(setOps.isMember(cacheKey, "5")).expectNext(true).verifyComplete(); 109 | } 110 | 111 | /** 112 | * SortedSet 데이터 구조 처리 - 순서 있음, value 중복 허용 안함 113 | */ 114 | @Test 115 | public void opsSortedSet() { 116 | ReactiveZSetOperations zsetOps = reactiveRedisTemplate.opsForZSet(); 117 | String cacheKey = "valueZSet"; 118 | 119 | // previous key delete - sync process 120 | redisTemplate.delete(cacheKey); 121 | 122 | // async process 123 | List> tuples = new ArrayList<>(); 124 | for (int i = 0; i < 10; i++) { 125 | tuples.add(new DefaultTypedTuple<>(String.valueOf(i), (double) i)); 126 | } 127 | StepVerifier.create(zsetOps.addAll(cacheKey, tuples)).expectNext(10L).verifyComplete(); 128 | StepVerifier.create(reactiveRedisTemplate.type(cacheKey)).expectNext(DataType.ZSET).verifyComplete(); 129 | StepVerifier.create(zsetOps.size(cacheKey)).expectNext(10L).verifyComplete(); 130 | StepVerifier.create(zsetOps.reverseRank(cacheKey, "9")).expectNext(0L).verifyComplete(); 131 | } 132 | 133 | /** 134 | * Geo 데이터 구조 처리 - 좌표 정보 처리, 타입은 zset으로 저장. 135 | */ 136 | @Test 137 | public void opsGeo() { 138 | ReactiveGeoOperations geoOps = reactiveRedisTemplate.opsForGeo(); 139 | String[] cities = {"서울", "부산"}; 140 | String[][] gu = {{"강남구", "서초구", "관악구", "동작구", "마포구"}, {"사하구", "해운대구", "영도구", "동래구", "수영구"}}; 141 | Point[][] pointGu = {{new Point(10, -10), new Point(11, -20), new Point(13, 10), new Point(14, 30), new Point(15, 40)}, {new Point(-100, 10), new Point(-110, 20), new Point(-130, 80), new Point(-140, 60), new Point(-150, 30)}}; 142 | String cacheKey = "valueGeo"; 143 | 144 | // previous key delete - sync process 145 | redisTemplate.delete(cacheKey); 146 | 147 | // async process 148 | Map memberCoordiateMap = new HashMap<>(); 149 | for (int x = 0; x < cities.length; x++) { 150 | for (int y = 0; y < 5; y++) { 151 | memberCoordiateMap.put(gu[x][y], pointGu[x][y]); 152 | } 153 | } 154 | StepVerifier.create(geoOps.add(cacheKey, memberCoordiateMap)).expectNext(10L).verifyComplete(); 155 | StepVerifier.create(geoOps.distance(cacheKey, "강남구", "동작구")).expectNextMatches(x -> x.getValue() == 4469610.0767).verifyComplete(); 156 | StepVerifier.create(geoOps.position(cacheKey, "동작구")).expectNextMatches(x -> x.getX() == 14.000001847743988 && x.getY() == 30.000000249977013).verifyComplete(); 157 | } 158 | 159 | /** 160 | * HyperLogLog 데이터 구조 처리 - 집합의 원소의 개수 추정, 타입은 string으로 저장. 161 | */ 162 | @Test 163 | public void opsHyperLogLog() { 164 | ReactiveHyperLogLogOperations hyperLogLogOps = reactiveRedisTemplate.opsForHyperLogLog(); 165 | String cacheKey = "valueHyperLogLog"; 166 | 167 | // previous key delete - sync process 168 | redisTemplate.delete(cacheKey); 169 | 170 | // async process 171 | String[] arr = {"1", "2", "2", "3", "4", "5", "5", "5", "5", "6", "7", "7", "7"}; 172 | StepVerifier.create(hyperLogLogOps.add(cacheKey, arr)).expectNext(1L).verifyComplete(); 173 | StepVerifier.create(hyperLogLogOps.size(cacheKey)).expectNext(7L).verifyComplete(); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/test/java/com/redis/cluster/RedisClusterTest.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster; 2 | 3 | import com.redis.cluster.entity.redis.Student; 4 | import com.redis.cluster.repo.redis.StudentRedisRepo; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.data.geo.Distance; 12 | import org.springframework.data.geo.Point; 13 | import org.springframework.data.redis.connection.DataType; 14 | import org.springframework.data.redis.core.*; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.time.LocalDateTime; 18 | import java.time.ZoneId; 19 | import java.util.*; 20 | import java.util.concurrent.TimeUnit; 21 | 22 | import static org.hamcrest.Matchers.greaterThan; 23 | import static org.junit.Assert.*; 24 | 25 | @RunWith(SpringRunner.class) 26 | @SpringBootTest 27 | public class RedisClusterTest { 28 | 29 | private Logger log = LoggerFactory.getLogger(this.getClass()); 30 | 31 | @Autowired 32 | private RedisTemplate redisTemplate; 33 | 34 | @Autowired 35 | private StudentRedisRepo redisRepo; 36 | 37 | /** 38 | * 문자 데이터 구조 처리 39 | */ 40 | @Test 41 | public void opsValue() { 42 | ValueOperations valueOps = redisTemplate.opsForValue(); 43 | Collection cacheKeys = new ArrayList<>(); 44 | String cacheKey = "value_"; 45 | for (int i = 0; i < 10; i++) { 46 | cacheKeys.add(cacheKey + i); 47 | valueOps.set(cacheKey + i, String.valueOf(i), 60, TimeUnit.SECONDS); 48 | } 49 | List values = valueOps.multiGet(cacheKeys); 50 | assertNotNull(values); 51 | assertEquals(10, values.size()); 52 | log.info("##### opsValue #####"); 53 | log.info("{}", values); 54 | } 55 | 56 | /** 57 | * List 데이터 구조 처리 - 순서 있음. value 중복 허용 58 | */ 59 | @Test 60 | public void opsList() { 61 | ListOperations listOps = redisTemplate.opsForList(); 62 | String cacheKey = "valueList"; 63 | for (int i = 0; i < 10; i++) 64 | listOps.leftPush(cacheKey, String.valueOf(i)); 65 | 66 | assertSame(DataType.LIST, redisTemplate.type(cacheKey)); 67 | assertSame(10L, listOps.size(cacheKey)); 68 | log.info("##### opsList #####"); 69 | log.info("{}", listOps.range(cacheKey, 0, 10)); 70 | assertEquals("0", listOps.rightPop(cacheKey)); 71 | assertEquals("9", listOps.leftPop(cacheKey)); 72 | assertEquals(true, redisTemplate.delete(cacheKey)); 73 | } 74 | 75 | /** 76 | * Hash 데이터 구조 처리 - 순서 없음. key 중복허용 안함, value 중복 허용 77 | */ 78 | @Test 79 | public void opsHash() { 80 | HashOperations hashOps = redisTemplate.opsForHash(); 81 | String cacheKey = "valueHash"; 82 | for (int i = 0; i < 10; i++) 83 | hashOps.put(cacheKey, "key_" + i, "value_" + i); 84 | 85 | assertSame(DataType.HASH, redisTemplate.type(cacheKey)); 86 | assertSame(10L, hashOps.size(cacheKey)); 87 | log.info("##### opsHash #####"); 88 | Set hkeys = hashOps.keys(cacheKey); 89 | for (String hkey : hkeys) { 90 | log.info("{} / {}", hkey, hashOps.get(cacheKey, hkey)); 91 | } 92 | 93 | assertEquals("value_5", hashOps.get(cacheKey, "key_5")); 94 | assertSame(1L, hashOps.delete(cacheKey, "key_5")); 95 | assertSame(null, hashOps.get(cacheKey, "key_5")); 96 | } 97 | 98 | /** 99 | * Set 데이터 구조 처리 - 순서 없음, value 중복 허용 안함 100 | */ 101 | @Test 102 | public void opsSet() { 103 | SetOperations setOps = redisTemplate.opsForSet(); 104 | String cacheKey = "valueSet"; 105 | for (int i = 0; i < 10; i++) 106 | setOps.add(cacheKey, String.valueOf(i)); 107 | 108 | assertSame(DataType.SET, redisTemplate.type(cacheKey)); 109 | assertSame(10L, setOps.size(cacheKey)); 110 | 111 | log.info("##### opsSet #####"); 112 | log.info("{}", setOps.members(cacheKey)); 113 | 114 | assertEquals(true, setOps.isMember(cacheKey, "5")); 115 | } 116 | 117 | /** 118 | * SortedSet 데이터 구조 처리 - 순서 있음, value 중복 허용 안함 119 | */ 120 | @Test 121 | public void opsSortedSet() { 122 | ZSetOperations zsetOps = redisTemplate.opsForZSet(); 123 | String cacheKey = "valueZSet"; 124 | for (int i = 0; i < 10; i++) 125 | zsetOps.add(cacheKey, String.valueOf(i), i); 126 | 127 | assertSame(DataType.ZSET, redisTemplate.type(cacheKey)); 128 | assertSame(10L, zsetOps.size(cacheKey)); 129 | log.info("##### opsSortedSet #####"); 130 | log.info("{}", zsetOps.range(cacheKey, 0, 10)); 131 | assertSame(0L, zsetOps.reverseRank(cacheKey, "9")); 132 | } 133 | 134 | /** 135 | * Geo 데이터 구조 처리 - 좌표 정보 처리, 타입은 zset으로 저장. 136 | */ 137 | @Test 138 | public void opsGeo() { 139 | GeoOperations geoOps = redisTemplate.opsForGeo(); 140 | String[] cities = {"서울", "부산"}; 141 | String[][] gu = {{"강남구", "서초구", "관악구", "동작구", "마포구"}, {"사하구", "해운대구", "영도구", "동래구", "수영구"}}; 142 | Point[][] pointGu = {{new Point(10, -10), new Point(11, -20), new Point(13, 10), new Point(14, 30), new Point(15, 40)}, {new Point(-100, 10), new Point(-110, 20), new Point(-130, 80), new Point(-140, 60), new Point(-150, 30)}}; 143 | String cacheKey = "valueGeo"; 144 | 145 | // previous key delete 146 | redisTemplate.delete(cacheKey); 147 | 148 | for (int x = 0; x < cities.length; x++) { 149 | for (int y = 0; y < 5; y++) { 150 | geoOps.add(cacheKey, pointGu[x][y], gu[x][y]); 151 | } 152 | } 153 | 154 | log.info("##### opsGeo #####"); 155 | Distance distance = geoOps.distance(cacheKey, "강남구", "동작구"); 156 | assertNotNull(distance); 157 | assertEquals(4469610.0767, distance.getValue(), 4); 158 | log.info("Distance : {}", distance.getValue()); 159 | List position = geoOps.position(cacheKey, "동작구"); 160 | assertNotNull(position); 161 | for (Point point : position) { 162 | assertEquals(14.000001847743988d, point.getX(), 4); 163 | assertEquals(30.000000249977013d, point.getY(), 4); 164 | log.info("Position : {} x {}", point.getX(), point.getY()); 165 | } 166 | } 167 | 168 | /** 169 | * HyperLogLog 데이터 구조 처리 - 집합의 원소의 개수 추정, 타입은 string으로 저장. 170 | */ 171 | @Test 172 | public void opsHyperLogLog() { 173 | HyperLogLogOperations hyperLogLogOps = redisTemplate.opsForHyperLogLog(); 174 | String cacheKey = "valueHyperLogLog"; 175 | String[] arr1 = {"1", "2", "2", "3", "4", "5", "5", "5", "5", "6", "7", "7", "7"}; 176 | hyperLogLogOps.add(cacheKey, arr1); 177 | log.info("##### opsHyperLogLog #####"); 178 | log.info("count : {}", hyperLogLogOps.size(cacheKey)); 179 | redisTemplate.delete(cacheKey); 180 | } 181 | 182 | @Test 183 | public void commonCommand() { 184 | ValueOperations valueOps = redisTemplate.opsForValue(); 185 | valueOps.set("key1", "key1value"); 186 | valueOps.set("key2", "key2value"); 187 | // Key 타입 조회. 188 | assertEquals(DataType.STRING, redisTemplate.type("key1")); 189 | // 존재하는 Key의 개수를 반환. 190 | assertSame(2L, redisTemplate.countExistingKeys(Arrays.asList("key1", "key2", "key3"))); 191 | // Key가 존재하는지 확인 192 | assertTrue(redisTemplate.hasKey("key1")); 193 | // Key 만료 날짜 세팅 194 | assertTrue(redisTemplate.expireAt("key1", Date.from(LocalDateTime.now().plusDays(1L).atZone(ZoneId.systemDefault()).toInstant()))); 195 | // Key 만료 시간 세팅 196 | assertTrue(redisTemplate.expire("key1", 60, TimeUnit.SECONDS)); 197 | // Key 만료 시간 조회 198 | assertThat(redisTemplate.getExpire("key1"), greaterThan(0L)); 199 | // Key 만료 시간 해제 200 | assertTrue(redisTemplate.persist("key1")); 201 | // Key 만료시간이 세팅 안되어있는경우 -1 반환 202 | assertSame(-1L, redisTemplate.getExpire("key1")); 203 | // Key 삭제 204 | assertTrue(redisTemplate.delete("key1")); 205 | // Key 일괄 삭제 206 | assertThat(redisTemplate.delete(Arrays.asList("key1", "key2", "key3")), greaterThan(0L)); 207 | } 208 | 209 | @Test 210 | public void redisHash_Insert() { 211 | long studentId = 1L; 212 | String name = "행복하라"; 213 | Student student = Student.builder().studentId(studentId).name(name).build(); 214 | redisRepo.save(student); 215 | 216 | Student cachedStudent = redisRepo.findById(studentId).orElse(null); 217 | assertNotNull(cachedStudent); 218 | assertEquals(1L, cachedStudent.getStudentId()); 219 | assertEquals(name, cachedStudent.getName()); 220 | } 221 | 222 | @Test 223 | public void redisHash_Update() { 224 | long studentId = 1L; 225 | String name = "행복하라"; 226 | Student student = Student.builder().studentId(studentId).name(name).build(); 227 | student.update("정직하라"); 228 | redisRepo.save(student); 229 | 230 | Student cachedStudent = redisRepo.findById(studentId).orElse(null); 231 | assertNotNull(cachedStudent); 232 | assertEquals(1L, cachedStudent.getStudentId()); 233 | assertEquals("정직하라", cachedStudent.getName()); 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/test/java/com/redis/cluster/controller/RedisControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.redis.cluster.controller; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.redis.cluster.entity.User; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.junit.After; 7 | import org.junit.Before; 8 | import org.junit.FixMethodOrder; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.junit.runners.MethodSorters; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.json.JacksonJsonParser; 14 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.test.context.junit4.SpringRunner; 18 | import org.springframework.test.web.servlet.MockMvc; 19 | import org.springframework.test.web.servlet.MvcResult; 20 | 21 | import java.util.Collections; 22 | 23 | import static org.hamcrest.Matchers.greaterThan; 24 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 25 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 26 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 27 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 28 | 29 | 30 | @Slf4j 31 | @RunWith(SpringRunner.class) 32 | @SpringBootTest 33 | @AutoConfigureMockMvc 34 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 35 | public class RedisControllerTest { 36 | 37 | @Autowired 38 | private MockMvc mockMvc; 39 | 40 | @Autowired 41 | private ObjectMapper objectMapper; 42 | 43 | private long msrl; 44 | 45 | @Before 46 | public void setUp() throws Exception { 47 | User user = User.builder() 48 | .uid("happydaddy@naver.com") 49 | .name("happydaddy") 50 | .password("password") 51 | .roles(Collections.singletonList("ROLE_USER")) 52 | .build(); 53 | MvcResult action = mockMvc.perform(post("/redis/user") 54 | .header("Accept", "application/json;charset=UTF-8") 55 | .contentType(MediaType.APPLICATION_JSON) 56 | .content(objectMapper.writeValueAsString(user))) 57 | .andDo(print()) 58 | .andExpect(status().isOk()) 59 | .andExpect(jsonPath("$.msrl").value(greaterThan(0))) 60 | .andExpect(jsonPath("$.uid").value("happydaddy@naver.com")) 61 | .andExpect(jsonPath("$.name").value("happydaddy")) 62 | .andExpect(jsonPath("$.roles").isArray()) 63 | .andReturn(); 64 | 65 | String resultString = action.getResponse().getContentAsString(); 66 | JacksonJsonParser jsonParser = new JacksonJsonParser(); 67 | msrl = Long.valueOf(jsonParser.parseMap(resultString).get("msrl").toString()); 68 | } 69 | 70 | @Test 71 | public void A_getUser() throws Exception { 72 | mockMvc.perform(get("/redis/user/" + msrl)) 73 | .andDo(print()) 74 | .andExpect(status().isOk()) 75 | .andExpect(jsonPath("$.msrl").value(msrl)) 76 | .andExpect(jsonPath("$.uid").value("happydaddy@naver.com")) 77 | .andExpect(jsonPath("$.name").value("happydaddy")) 78 | .andExpect(jsonPath("$.roles[0]").value("ROLE_USER")); 79 | } 80 | 81 | @Test 82 | public void B_putUser() throws Exception { 83 | User user = User.builder() 84 | .msrl(msrl) 85 | .uid("happydaddy@naver.com") 86 | .name("happydaddy_re") 87 | .roles(Collections.singletonList("ROLE_ADMIN")).build(); 88 | mockMvc.perform(put("/redis/user") 89 | .header("Accept", "application/json;charset=UTF-8") 90 | .contentType(MediaType.APPLICATION_JSON) 91 | .content(objectMapper.writeValueAsString(user))) 92 | .andDo(print()) 93 | .andExpect(status().isOk()) 94 | .andExpect(jsonPath("$.msrl").value(msrl)) 95 | .andExpect(jsonPath("$.uid").value("happydaddy@naver.com")) 96 | .andExpect(jsonPath("$.name").value("happydaddy_re")) 97 | .andExpect(jsonPath("$.roles[0]").value("ROLE_ADMIN")); 98 | } 99 | 100 | @After 101 | public void delUser() throws Exception { 102 | mockMvc.perform(delete("/redis/user/" + msrl)) 103 | .andDo(print()) 104 | .andExpect(status().isOk()); 105 | 106 | } 107 | } -------------------------------------------------------------------------------- /src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | %-5level %d{HH:mm:ss} %logger{15}.%method:%line - %msg%n 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | --------------------------------------------------------------------------------