티스토리 뷰

지난번에 Redis 설치와 간단한 테스트를 해보았고 이번에는 설치한 Redis를 springboot와 연동하는 방법에 대해 알아보겠다. springboot의 장점 중 하나는 다른 솔루션과의 integration이 아닐까 싶다. 전에 작성한 application.yml 파일에서 integration 할 수 있는 property들에 대해서 봤는데 여기에 있는 솔루션들은 모두 쉽게 springboot 환경에서 사용할 수 있다고 보면 된다. Redis도 그중 하나다. 


1. 사전작업 - Redis 설치

Redis 구동

일단 위의 링크를 따라가서 Redis를 설치하고 구동을 시켜놓자. 그리고 잘 되는지 테스트도 해보자.

일단 다음과 같이 Redis 에 값을 하나 넣어 놓았다. 

 

redis set get

잘 된다면 springboot와 연동하기 위한 다음 단계로 넘어간다. 

 

2. Spring Starter Project 생성

그다음은 springboot app을 생성하는 것부터 시작해보도록 하자. 사용중인 springboot app이 있다면 아래에 나오는 dependency만 추가해주면 된다. 

 

Spring Starter Project
redis sample project 생성
redis starter 추가

Spring WebSpring Data Redis starter를 추가해준다. Finish!

 

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

pom.xml에는 spring-boot-starter-data-redis, spring-boot-starter-web dependency가 추가되음을 확인할 수 있다. 

 

3. Springboot에서의 Redis 설정 (application.properties or yml)

spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=8 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

property 설정은 위와 같은 방식으로 해주면 된다. 필자는 로컬에 Redis를 설치해서 host가 localhost이고 실제 Redis를 설치한 서버의 정보를 입력해주면 된다. password는 설정 했으면 넣어주고 아니라면 설정하지 않아도 된다. 그 외에 접속에 대한 설정을 할 수 있다. 

 

Springboot 2.0 버전 이상은 위와 같이 application.properties 설정만 해주면 되는데 그 아래의 버전은 RedisConnectionFactory, RedisTemplate, StringRedisTemplate 등을 추가로 설정을 해줘야 한다. 2.0 이상의 버전에서는 AutoConfiguration이 이 작업을 대신 해준다. 그래서 그냥 이 bean들을 가져다 쓰기만 하면 된다. 

springboot 2.0 아래의 버전은 다음과 같은 설정을 추가해주자. 

@Configuration
public class RedisConfig {

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory();
        return lettuceConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
        stringRedisTemplate.setValueSerializer(new StringRedisSerializer());
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory());
        return stringRedisTemplate;
    }
}

 

4-1. Springboot와 Redis 연동 코드작성 (Redis data get)

위와 같이 설정이 다 끝났으면 이제 어떤 일을 수행할지 코드를 작성해보자. 

 

Service Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisSampleService {
	
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
	
    public void getRedisStringValue(String key) {
		
        ValueOperations<String, String> stringValueOperations = stringRedisTemplate.opsForValue();
        System.out.println("Redis key : " + key);
        System.out.println("Redis value : " + stringValueOperations.get(key));
    }
}

Redis와 연동하기 위한 RedisTemplate을 이용하여 위와 같이 아주 간단하게 springboot와 연동을 할 수 있다. RedisTemplate 중에서도 가장 많이 쓰이는 StringRedisTemplate을 이용하였다. 

 

StringRedisTemplate 

StringRedisTemplate을 통해 다양한 타입의 자료구조를 사용할 수 있다. 위와 같은 메서드를 사용하면 해당 자료구조의 직렬화 및 역직렬화를 할 수 있어서 유용하다. 

실제로 Redis 관련 로직은 두줄이 추가됐을 정도로 아주 간단하게 springboot와 연동하여 사용할 수 있다. 

 

Controller Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.RedisSampleService;

@RestController
public class RedisSampleController {
    
    @Autowired
    private RedisSampleService redisSampleService;

    @PostMapping(value = "/getRedisStringValue")
    public void getRedisStringValue(String key) {
        redisSampleService.getRedisStringValue(key);
    }
}

Controller는 일반적인 RestController의 모습과 동일하다. 위에서 정의한 Service Class를 호출하기 위한 용도로 사용한다. key라는 변수를 받는데 이것은 Redis에 요청할 값을 받는 것이다. 작성을 다 했으면 서비스를 기동하자. 

 

 

5-1. Springboot와 Redis 연동 테스트 (get)

연동 테스트는 부메랑을 사용해서 했다. 

 

Redis key 값 전달

key로 맨 위에 Redis 설치하고 테스트할때 넣어뒀던 banana 라는 것을 사용해본다. 그리고 이 액션을 날려보자. 혹시나 MISCONF 관련 오류가 발생한다면 이 글을 참조해서 오류를 수정하도록 하자. 

 

Console Result

banana에 대한 value인 yellow를 잘 가지고 오는 것을 확인할 수 있다. 정상적으로 연동이 완료되었다. 


Redis에 있는 데이터를 가져오는 부분에 대해서는 위와 같이 테스트를 하였고 이제는 Redis에 set도 하고 get도 하는 샘플에 대해서 살펴보자. 위의 코드에서 크게 달라지는 부분이 없다. 

 

4-2. Springboot와 Redis 연동 코드작성 (Redis data set)

Redis data를 get 하는것과 거의 동일하다. set만 해주면 된다. 

Service Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisSampleService {
	
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
	
    public void setRedisStringValue(String key, String value) {		
        ValueOperations<String, String> stringValueOperations = stringRedisTemplate.opsForValue();
        stringValueOperations.set(key, value);
        System.out.println("Redis key : " + key);
        System.out.println("Redis value : " + stringValueOperations.get(key));
    }
}

stringValueOperations.set 만 해주면 된다. 

 

Controller Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.RedisSampleService;

@RestController
public class RedisSampleController {
    
    @Autowired
    private RedisSampleService redisSampleService;

    @PostMapping(value = "/setRedisStringValue")
    public void setRedisStringValue(String key, String value) {
    	redisSampleService.setRedisStringValue(key, value);
    }
}

get과 거의 동일하지만 여기서는 key와 value를 모두 받아 넘긴다. 

 

5-2. Springboot와 Redis 연동 테스트 (set)

위와 같이 요청을 보내서 

 

이런 결과값을 정상적으로 받을 수 있었다. 

 

정말 간단하게 springboot와 연동시킬 수 있다. 간단하다. 예전에는 다른 OSS와의 integration이 어려운점이 많았었는데 요즘은 참 좋아진것 같다. 

 

다음으로는 Redis를 활용해 Session Clustering을 하는 예제를 살펴보도록 하자. 

 

Springboot + Redis 연동하는 예제 (2) 세션 클러스터링

Springboot + Redis 연동하는 예제 (1) 기본 지난번에 Redis 설치와 간단한 테스트를 해보았고 이번에는 설치한 Redis를 springboot와 연동하는 방법에 대해 알아보겠다. springboot의 장점 중 하나는 다른 솔루

oingdaddy.tistory.com

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
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