Database
[Redis] Redis ๊ธฐ๋ณธ ๊ฐ๋ ๊ณผ ์คํ๋ง๋ถํธ ์ฌ์ฉ ์์
carsumin
2026. 2. 12. 08:40
Redis๋?
- Redis๋ ๋ฉ๋ชจ๋ฆฌ ๊ธฐ๋ฐ Key-Value ์ ์ฅ์ (์ธ๋ฉ๋ชจ๋ฆฌ)
- ๋น ๋ฅธ ์กฐํ๊ฐ ํ์ํ ๋ฐ์ดํฐ๋ฅผ ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅํ๋ ๊ณ ์ฑ๋ฅ ๋ฐ์ดํฐ ์ ์ฅ์
Redis ์ฌ์ฉ ์ด์
- ์บ์ (Cache)
- DB ๋ถํ ๊ฐ์
- ์๋ต ์๋ ํฅ์
- ์) ์ธ๊ธฐ ๊ฒ์๊ธ ์กฐํ์, ์ธ๊ธฐ ์ํ ๋ชฉ๋ก, ์ฌ์ฉ์ ์ธ์ ์ ๋ณด ๋ฑ
- ๋ถ์ฐ ๋ฝ (Distributed Lock)
- ์ฌ๋ฌ ์๋ฒ์์ ๋์์ ๊ฐ์ ์์์ ๋ณ๊ฒฝํ์ง ๋ชปํ๊ฒ ์ ์ด
- ์) ์ฌ๊ณ ์ฐจ๊ฐ, ํฌ์ธํธ ์ฐจ๊ฐ
- ์ธ์
์ ์ฅ์ / ํ ํฐ ์ ์ฅ์
- ๋ก๊ทธ์ธ ์ธ์ , RefreshToken ์ ์ฅ
Redis ๊ธฐ๋ณธ ๊ตฌ์กฐ
- Redis๋ ํ
์ด๋ธ์ด ์๋๋ผ Key-Value ๊ตฌ์กฐ
- Key๋ ๋ฌธ์์ด
- Value๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ฌธ์์ด
- TTL(๋ง๋ฃ ์๊ฐ) ์ค์ ๊ฐ๋ฅ -> ์๋ ์ญ์
key → value
"USER:1" → {name: "ํ๊ธธ๋", age: 25}
"RT:100" → "eyJhbGciOiJIUzI1Ni..."
"POST:VIEW:10" → 1234
Spring Boot + Redis ์์ ์ฝ๋ (RefreshToken)
- ์์กด์ฑ ์ถ๊ฐ (build.gradle)
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
- application.yml
spring:
data:
redis:
host: localhost
port: 6379
- RedisConfig
- Spring์์ Redis๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ์ฐ๊ฒฐ ์ค์
- StringRedisTemplate = Redis ์ ์ฉ ํด๋ผ์ด์ธํธ ๊ฐ์ฒด
- Redis ์ง๋ ฌํ ๋ฐฉ์์ ์ปค์คํฐ๋ง์ด์ง ํ ๋
- JSON ์ ์ฅ, ๊ฐ์ฒด ์ ์ฅ
- RedisTemplate ์ค์ ๋ณ๊ฒฝ
- ์ฌ๋ฌ Redis ์๋ฒ๋ฅผ ์ธ ๋ (๊ธฐ๋ณธ Redis + ์บ์์ฉ Redis ๋ถ๋ฆฌ)
- ์ด์ ํ๊ฒฝ์์ ์ธ๋ฐํ ํ๋์ด ํ์ํ ๋
package com.draftory.global.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.StringRedisTemplate;
@Configuration
public class RedisConfig {
@Bean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
- RefreshTokenStore
package com.draftory.global.auth;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
@Component
public class RefreshTokenStore {
private final StringRedisTemplate redisTemplate;
public RefreshTokenStore(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* Redis Key ์์ฑ ๊ท์น
* ์) RT:100 (userId = 100)
*/
private String key(Long userId) {
return "RT:" + userId;
}
/**
* Refresh Token ์ ์ฅ
*/
public void save(Long userId, String refreshToken, long ttlSeconds) {
redisTemplate.opsForValue()
.set(key(userId), refreshToken, Duration.ofSeconds(ttlSeconds));
}
/**
* Refresh Token ์กฐํ
*/
public String get(Long userId) {
return redisTemplate.opsForValue().get(key(userId));
}
/**
* Refresh Token ์ญ์ (๋ก๊ทธ์์ ์ ์ฌ์ฉ)
*/
public void delete(Long userId) {
redisTemplate.delete(key(userId));
}
}