Spring

springboot에서 redis 다루기

스프링 스타터를 통해서 프로젝트를 만들고 사용하지는 IDE에서 열어줍니다.

테스트 환경에서 embedded redis 사용하기 위해서 아래의 의존성을 추가해 줍니다.

implementation 'it.ozimov:embedded-redis:0.7.2'

 

redis을 repository로 사용하기 위해서 configuartion 설정을 해줍니다.

위와 같은 이유로 lettuce를 사용하였습니다.

@Configuration
@EnableRedisRepositories
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(new RedisStandaloneConfiguration(host, port));
    }

    @Bean
    RedisTemplate<? ,?> redisTemplate() {
        RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }
}

 

test하위 resource안에 yml 설정 추가

spring:
  redis:
    host: localhost
    port: 6379
@Getter
@RedisHash("point")
@ToString
public class Point implements Serializable {

    @Id
    private String id;
    private Long amount;
    private LocalDateTime refreshTime;

    @Builder
    public Point(String id, Long amount, LocalDateTime refreshTime) {
        this.id = id;
        this.amount = amount;
        this.refreshTime = refreshTime;
    }

    public void refresh(long amount, LocalDateTime refreshTime){
        if(refreshTime.isAfter(this.refreshTime)){ // 저장된 데이터보다 최신 데이터일 경우
            this.amount = amount;
            this.refreshTime = refreshTime;
        }
    }
}
public interface PointRedisRepository extends CrudRepository<Point, String> {
}
@SpringBootTest
class PointRedisRepositoryTest {

    @Autowired
    private PointRedisRepository pointRedisRepository;

    @AfterEach
    public void tearDown() {
        pointRedisRepository.deleteAll();
    }

    @Test
    public void 기본_등록_조회() {
        //given
        String id = "wellbell";
        LocalDateTime refreshTime = LocalDateTime.now();
        Point point = Point.builder()
                .id(id)
                .amount(1000L)
                .refreshTime(refreshTime)
                .build();

        pointRedisRepository.save(point);

        Point findPoint = pointRedisRepository.findById(id).get();
        assertAll("기본 등록 조회",
                () -> assertThat(findPoint.getAmount()).isEqualTo(1000L),
                () -> assertThat(findPoint.getRefreshTime()).isEqualTo(refreshTime)
        );
    }
}

aftereach 부분을 주석처리하시면 redis-cli를 통해서 해당 값을 확인 하실수 있습니다.

 

redisTemplate을 통해서 값을 컨트롤 할수 있습니다.

@SpringBootTest
public class RedisTemplateTest {


    @Autowired
    RedisTemplate redisTemplate;

    @Test
    public void Strings_구조_테스트() {
        //given
        String key = "point";
        String id = "wellbell";
        long amount = 2000L;
        LocalDateTime time = LocalDateTime.now();
        Point point = Point.builder()
                .id(id)
                .amount(amount)
                .refreshTime(time)
                .build();

        ValueOperations<String, Point> stringStringValueOperations = redisTemplate.opsForValue();
        stringStringValueOperations.set(key, point);

        //when
        Point findPoint = stringStringValueOperations.get(key);

        //then
        assertAll("Strings_구조_테스트",
                () -> assertThat(findPoint.getId()).isEqualTo(id),
                () -> assertThat(findPoint.getAmount()).isEqualTo(amount),
                () -> assertThat(findPoint.getRefreshTime()).isEqualTo(time)
        );
    }

    @Test
    public void testList() {
        //given
        String key = "point";
        String id = "wellbell";
        long amount = 2000L;
        LocalDateTime time = LocalDateTime.now();
        Point point = Point.builder()
                .id(id)
                .amount(amount)
                .refreshTime(time)
                .build();

        ListOperations<String, Point> stringStringListOperations = redisTemplate.opsForList();
        stringStringListOperations.rightPush(key, point);
        stringStringListOperations.rightPush(key, point);
        stringStringListOperations.rightPush(key, point);
        stringStringListOperations.rightPush(key, point);
        stringStringListOperations.rightPush(key, point);

        //when
        List<Point> range = stringStringListOperations.range(key, 0, 9);

        //then
        assertAll(
                () -> {
                    for (Point findPoint : range) {
                        assertAll(
                                () -> assertThat(findPoint.getId()).isEqualTo(key),
                                () -> assertThat(findPoint.getAmount()).isEqualTo(amount),
                                () -> assertThat(findPoint.getRefreshTime()).isEqualTo(time)
                        );
                    }
                }
        );
    }
}

'Spring' 카테고리의 다른 글

Spring에서 사용하는 어노테이션 정리  (0) 2021.05.29
Spring 트랜잭션 전파  (0) 2021.05.29
Spring Interceptor  (0) 2021.04.12
Spring Filter  (0) 2021.04.10
Spring AOP  (0) 2021.04.09