들어가며,
프로젝트에서 사용자 및 이메일 관련 로직을 담당하게 됬다.
구현을 하던 중, 이메일로 보낸 인증코드를 '검증' 하는 로직을 짜는데 Redis 라는 Nosql 비관계형 DB가 필요하게 되었다.
따라서 오늘은 Redis에 대하여 작성해 볼 것이다.
먼저 Cache의 개념부터 알면 좋다.
Cache 란
- 한번 읽은(처리된) 데이터를 임시로 저장하고, 필요에 따라 전송, 갱신, 삭제하는 기술이다.
- 보통 서버의 메모리를 사용하는 경우가 많다.
- 메모리를 사용하기 때문에 매번 Disk로부터 데이터를 조회하는 것보다 훨씬 빠른 I/O 성능을 얻을 수 있다.
- 하지만 서버가 다운되거나, 재부팅되는 경우 데이터가 사라지는 휘발성의 성격을 갖고 있다.
- 따라서 영속적으로 보관할 수 없는, 임시적으로 보관하고 빠르게 해당 정보에 접근하기 위한 용도로 사용되어야 한다. Redis의 경우, 주기적으로 Disk에 백업해 둘 수 있다.
Cache 장점
- 서버 간 불필요한 트래픽을 줄일 수 있다.
- 웹어플리케이션 서버의 부하를 감소시킨다.
- 어플리케이션의 빠른 처리성능(조회)을 확보해 궁극적으로 고객에게 쾌적한 서비스 경험을 제공한다.
Cache의 대상이 되는 데이터
- 단순한, 또는 단순한 구조의 데이터 : 정보의 단순성
- 반복적으로 동일하게 제공되어야 하는 데이터 : 빈번한 동일 요청의 반복
- 변경 주기가 빈번하지 않고 단위처리 시간이 오래걸리는 정보 : 높은 단위처리 비용
- 정보의 최신화가 반드시 실시간으로 이루어지지 않아도 서비스 품질에 영향을 거의 주지 않는 정보
→ 해당 조건들 중 2개 이상 포함되는 성격의 데이터이면 Cache 적용을 적극적으로 고려해 볼 수 있다.
- 예시
- 검색어, 인기 상품, 베스트 셀러 등
- 방문자 수, 조회 수, 추천 수
- 1회성 인증정보 (SMS 본인인증, IP 정보 등)
Cache 사용 시 주의할 점
- 캐싱할 정보의 선택
- 캐싱할 정보의 유효기간 (TTL, Time To Live) 설정
- 캐싱할 정보의 갱신 시점
→ 서비스 설계 시, 특히 백엔드의 경우 API 서비스의 기능 설계 단계부터 Cache 정책을 수립해두는게 좋다.
→ 어떤 정보를 Cache로 적용할지?, 해당 정보들을 어떤 시점에 어떤 주기로 갱신, 삭제할 지? ⇒ 캐싱 전략
📌Redis 란?
Redis는 Remote Dictionary Server의 약자로, 키-값" 구조의 비정형 데이터를 저장하고 관리하기 위한 오픈소스 기반의 비관계형 데이터베이스 관리 시스템(DBMS)이다.
📌 Redis를 사용한 이유
인메모리 데이터 저장소로 빠른 응답 시간, 데이터 만료 기능을 제공하기 때문에 제한된 시간 동안만 유효한 이메일 관련 데이터를 저장하기 적합하다고 판단하였다.
📌 그렇다면 Redis를 직접 사용해보자.
build.gradle 파일에 spring-boot-starter-data-redis 의존성을 추가해주었다.
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
application.properties 에 사용할 레디스의 호스트와 포트를 지정해준다.
spring.data.redis.cache.host=localhost
spring.data.redis.cache.port=6379
package com.swyp.kiwoyu.global.config;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@RequiredArgsConstructor
@Configuration
@EnableRedisRepositories
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate() {
return new StringRedisTemplate(redisConnectionFactory());
}
}
레디스 템플릿 사용하기
레디스 템플릿은 사용하는 자료구조마다 제공하는 메서드가 다르기 때문에 객체를 만들어서 레디스의 자료구조 타입에 맞는 메소드를 사용하면 된다.
StingRedisTemplate 클래스 구조
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.data.redis.core;
import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
public class StringRedisTemplate extends RedisTemplate<String, String> {
public StringRedisTemplate() {
this.setKeySerializer(RedisSerializer.string());
this.setValueSerializer(RedisSerializer.string());
this.setHashKeySerializer(RedisSerializer.string());
this.setHashValueSerializer(RedisSerializer.string());
}
public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
this.setConnectionFactory(connectionFactory);
this.afterPropertiesSet();
}
protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}
RedisUtil.java
package com.swyp.kiwoyu.global.util;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
private final StringRedisTemplate redisTemplate;
public RedisUtil(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void setDataExpire(String key, String value, long duration) {
redisTemplate.opsForValue().set(key, value, duration, TimeUnit.MINUTES);
}
public String getData(String key) {
return redisTemplate.opsForValue().get(key);
}
public void deleteData(String key) {
redisTemplate.delete(key);
}
}
이 클래스는 Spring Boot 애플리케이션에서 Redis와 상호 작용한다.
RedisUtil 클래스는 Redis와 상호 작용하기 위한 간단한 유틸리티 클래스로, 키-값 데이터를 저장, 조회, 삭제하는 기능을 제공합니다. 이 클래스는 StringRedisTemplate을 사용하여 Redis 서버와 연결하고, 데이터를 관리합니다. 예를 들어, 특정 데이터를 일정 시간 동안 캐시로 저장하거나, 필요할 때 데이터를 조회하고, 더 이상 필요하지 않을 때 데이터를 삭제할 수 있습니다.
참고 블로그 및 사이트
Redis 다운로드: https://github.com/microsoftarchive/redis/releases
Releases · microsoftarchive/redis
Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes - microsoftarchive/redis
github.com
https://ittrue.tistory.com/318
[Redis] 윈도우10 환경에서 레디스 설치하기
Redis 설치 프로그램 다운로드 아래 링크에 접속하여 msi 확장자의 Redis 설치 프로그램을 다운로드한다. https://github.com/microsoftarchive/redis/releases Releases · microsoftarchive/redis Redis is an in-memory database that
ittrue.tistory.com
'개발일지 > DB' 카테고리의 다른 글
[DB] PostgreSQL과 MySQL의 차이 (퍼옴) (0) | 2024.09.23 |
---|---|
[DB] Redis란? 사용하는 이유 (1) | 2024.05.12 |