Free Lines Arrow
본문 바로가기
DataBase/Redis

[Redis] Redis Spring boot 간단예제

by skahn1215 2023. 2. 21.
728x90
반응형

 Redis Spring boot

  • 레디스를 스프링 부트와 연동하고 작업을 해보자.

 

실제 구현해보기

yml 파일 작성

spring:
  redis:
    data:
      host: localhost
      port: 6379

 

Redis template config 등록

  • RedisTemplate 이란 스프링과 레디스 사이에서 쓰레드 세이프한 브리지를 제공해 주는 역할을 한다.
  • 커넥션을 관리 해주어 레디스의 커넥션을 알아서 열고 닫아 준다.
  • 그리고 위에 작성한 yaml 파일에 있는 정보를 읽어 알아서 커넥션도 맺어주는 역할을 한다.
package com.redis.practice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<?, ?> redisTemplate (RedisConnectionFactory connectionFactory) {
        RedisTemplate<?, ?> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        return template;
    }
}

 

 

Repository 작성

  • 우리는 bean 으로 등록해준 RedistTemplate 를 가져다 쓰기만 하면된다.
package com.redis.practice.repository;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class StringRepository {
    private final RedisTemplate<String, String> template;

    public void save(String key, String name) {
        template.opsForValue().set(key, name);
    }

    public String findByKey(String key) {
        return template.opsForValue().get(key);
    }
}

 

Test code 작성

package com.redis.practice.repository;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class StringRepositoryTest {

    @Autowired
    StringRepository stringRepository;

    @Test
    void StringSaveTest() {
        String key = "key1";
        String value = "value1";
        stringRepository.save(key, value);

        String foundValue = stringRepository.findByKey(key);
        Assertions.assertThat(foundValue).isEqualTo(value);
    }
}

 

 

 

참고:

https://developer.redis.com/develop/java/redis-and-spring-course/lesson_2

 

Introducing Spring Data Redis | The Home of Redis Developers

Objectives

developer.redis.com

728x90
반응형

'DataBase > Redis' 카테고리의 다른 글

[Redis] Redis 시작하기  (0) 2023.02.21
[Redis] Redis 란?  (0) 2023.02.08

댓글