[Redis] articles 실습 with Spring boot

RyECODING·2024년 8월 18일

MSA

목록 보기
8/15

실제 Entity 등은 만들지 않고, Redis에 데이터만 저장해서 새로운 Articles Spring Boot 프로젝트를 만들어보자!

  • Redis의 문자열은 저장된 데이터가 정수라면
    INCR, DECR 등으로 값을 쉽게 조정할 수 있다.

  • 추가로 존재하지 않는 데이터에 대해서 실행할 경우 0으로 초기화된다.

    INCR articles:{id}
    
  • 만약 날짜가 바뀔 때 데이터를 저장하고 싶다면,
    Key를 articles:{id}:today 등으로 만들고

    INCR articles:{id}:today
  • 날짜가 바뀌는 시점에 RENAME으로 해당 날짜를 기록하면 된다.

    RENAME articles:{id}:today articles:{id}:20XX-XX-XX

✔️ application.yml

spring:
  data:
    redis:
      port: 설정한 port번호
      host: localhost
      username: 설정한 username
      password: 설정한 password

✔️ RedisConfig.class

package com.redis.redis_mini_practice2;

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;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Integer> articleTemplate(
            RedisConnectionFactory redisConnectionFactory
    ) {
        RedisTemplate<String, Integer> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        
        //Key값 String으로 설정, 해당 코드 미작성 시 ��t article::1 이런 식으로 저장됨
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(new GenericToStringSerializer<>(Integer.class));
        return template;
    }
}

✔️ ArticleController.class

package com.redis.redis_mini_practice2;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/articles")
public class ArticleController {
    private final ValueOperations<String, Integer> ops;

    public ArticleController(
            RedisTemplate<String, Integer> articleTemplate
    ) {
        ops = articleTemplate.opsForValue();
    }

    @GetMapping("{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void read(@PathVariable("id") Long id) {
        ops.increment("article::%d".formatted(id));
    }
}
profile
례코드

0개의 댓글