spring Boot에서 Redis 연결하기
2024. 6. 28. 21:09ㆍTIL
✔오늘 배운 중요한 🔑 point
- RedisTemplate을 사용하여 데이터를 Redis에 저장하고 조회할 수 있다.
- Redis는 다양한 데이터 형식을 지원하는데 RedisTemplate는 이러한 데이터 형식들을 각각의 Redis 데이터 구조와 매핑하여 사용할 수 있다.
🎯 오늘 배운 내용
프로젝트 요구사항 중 회원가입시 해당 이메일로 인증 번호를 보내고 인증이 되야 정상적으로 회원가입이 되야하는 기능을 구현하기 위해서 인증번호를 메모리에 저장하기 위한 인메모리 저장소 Redis를 이용하였다.
Redis 설정
build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive")
}
Redis 의존성 추가
application.yml
spring:
jpa:
hibernate:
ddl-auto: update
show-sql: true
data:
redis:
host : redis-******.c****.ap-northeast-1-2.ec2.redns.redis-cloud.com:*****
port : 6379
redis 정보 추가
RedisConfig
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.repository.configuration.EnableRedisRepositories
@Configuration
@EnableRedisRepositories
class RedisConfig {
@Bean
fun redisConnectionFactory(): RedisConnectionFactory {
return LettuceConnectionFactory()
}
@Bean
fun redisTemplate(connectionFactory: RedisConnectionFactory): RedisTemplate<ByteArray, ByteArray> {
val template = RedisTemplate<ByteArray, ByteArray>()
template.setConnectionFactory(connectionFactory)
return template
}
}
@Bean
fun redisConnectionFactory(): RedisConnectionFactory {
return LettuceConnectionFactory()
}
LettuceConnectionFactory() 를 사용하여 redis에 연결하는 Connection Factory를 생성
redisConnectionFactory 함수는 RedisTemplate에 사용될 Redis 연결을 설정한다
@Bean
fun redisTemplate(connectionFactory: RedisConnectionFactory): RedisTemplate<ByteArray, ByteArray> {
val template = RedisTemplate<ByteArray, ByteArray>()
template.setConnectionFactory(connectionFactory)
return template
}
Redis 접근과 상호작용을 위한 RedisTemplate 클래스를 설정하고 반환한다
RedisConfig를 사용하여 Redis 데이터베이스와의 연결을 설정하고 Redis에 데이터를 인메모리 저장하고 접근할 수 있게 되었다.
🤔 어떻게 활용할까?
Redis 인메모리와, smtp 를 활용하여 효과적인 이메일 인증을 구현할 수 있게 되었다
📓 오늘의 한줄
"Character cannot be developed in ease and quiet. Only through experience of trial and suffering can the soul be strengthened, ambition inspired, and success achieved."
- Helen Keller -
'TIL' 카테고리의 다른 글
gitignore로 보안정보 숨기기 (0) | 2024.06.30 |
---|---|
Connection refused: getsockopt 오류 (0) | 2024.06.29 |
class java.lang.String cannot be cast to class 오류 (0) | 2024.06.27 |
.let (0) | 2024.06.26 |
CDN(Content Delivery Network) (0) | 2024.06.25 |