[Sampling] 1. Redis 예제

문정준's avatar
May 25, 2025
[Sampling] 1. Redis 예제

1. Redis 설치 - Docker 설치

 
 
  • Dockerfile 작성 후 터미널에서 명령어 입력하여 설치
notion image
 
 

Spring 프로젝트 제작 : Sampling

package com.example.demoapp; import jakarta.servlet.http.HttpSession; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Set; @RequiredArgsConstructor @RestController public class HelloController { private final RedisTemplate<String, String> redisTemplate; private final HttpSession session; @GetMapping("/health") public String healthCheck() { if (redisTemplate == null) return "No Redis Template"; else return "OK"; } @GetMapping("/save") public String save() { //redisTemplate.opsForValue().set("name", "ssar"); session.setAttribute("username", "cos"); return "OK"; } @GetMapping("/find") public String find() { // 키 값에 jsessionId가 붙어 있음 : username으로 찾을 수 없음 String name = session.getAttribute("username").toString(); return "Found name : " + name; } // String으로 저장된 key일 경우 값을 같이 보여줌 @GetMapping("/all-values") public List<String> getAllValues() { Set<String> keys = redisTemplate.keys("*"); if (keys == null || keys.isEmpty()) { return List.of("No keys found"); } List<String> result = new ArrayList<>(); for (String key : keys) { // String -> byte[] byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); // 타입 조회 String type = redisTemplate.getConnectionFactory().getConnection().type(keyBytes).code(); if ("string".equals(type)) { String value = (String) redisTemplate.opsForValue().get(key); result.add(key + " => " + value); } else { result.add(key + " => [not a string: " + type + "]"); } } return result; } }
 

Result

 
  • Docker (Redis)가 실행되어 있으면, Redis에 저장한 값이 잘 찾아짐
notion image
 
  • Docker가 꺼져 있으면, Redis 접근이 불가능하여 에러 발생
notion image
 
  • session에 저장할 경우 : Redis에 저장을 했는데도 값을 찾을 수 없음
    • session에 저장하면 자바에서는 이를 hash를 통한 단방향 암호화를 수행하기 때문
    • 키 값도 해시로 암호화 되어 있으므로, 키 값 그대로 입력해서 찾을 수 없음
notion image
 
  • session.getAttribute를 이용하여 jsessionId의 역직렬화를 통한 decoding이 필요
    • 직접 키 값으로 찾는 것이 아닌 session을 끌어오는 방식 : 기존 세션 접근 방식과 동일해 보임
    • 다만, 이 방식을 사용하면 진짜 서버의 session이 아닌 Redis에 저장됨
notion image
 
 
notion image
Share article

sxias