[Spring Boot #20] 스프링부트 레디스(Redis) 연동

레디스(Redis)

  • 레디스는 Key-Value 기반인 인메모리 데이터 저장소로서 주로 캐쉬 솔루션으로 쓰이고 있는 오픈 프로젝트 입니다.

  • 레디스를 이용하게 되면 JVM위에서 동작하지 않고 어떤 데이터를 캐싱할 수 있다. 따라서 GC대상이 되지 않고 그로 인한 오버헤드가 줄어드는 장점이 있다.

  • Redis는 기본적으로 스프링부트에 6379 포트로 설정되어 있다.

스프링부트와 레디스(Redis) 연동

의존성

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

  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
  </dependency>

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

레디스 도커 실행

docker run -p 6379:6379 --name redis_boot -d redis
$ docker exec -i -t redis_boot redis-cli

127.0.0.1:6379> keys *
(empty array)

코드

package org.kyhslam.springredis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class RedisRunner implements ApplicationRunner {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ValueOperations<String,String> values = redisTemplate.opsForValue();
        values.set("kyhslam", "dunk");
        values.set("springboot", "2.0");
        values.set("hello", "world");
    }
}
  • 스프링부트에서는 RedisTemplate, StringRedisTemplate를 통해 레디스에 십게 접근할 수 있다.
  • opsForValue를 통해서 레디스에 Key-Value 기반인 데이터를 캐싱하거나 그 값을 얻어올 수 있다.

결과

127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> keys *
1) "hello"
2) "kyhslam"
3) "springboot"
  • 참고로 빌드시 에러가 나면 application.properties에 아래의 내용을 명시해 주면 된다.
  • tool box 는 기본 IP는 192.168.99.100 로 localhost(127.0.0.1)와 다르기 때문에 아래의 properties를 추가 하면 정상작업 가능하다.
spring.redis.host=192.168.99.100
spring.redis.port=6379

댓글

Designed by JB FACTORY