Video in progress
What do you do to connect a Spring Boot application to Redis?
You add spring-boot-starter-data-redis and set the host/port in application.yml. After that Boot creates a Lettuce connection factory and a StringRedisTemplate on its own, and you just inject and use them.
📖 Answer
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
data:
redis:
host: localhost
port: 6379
password: ${REDIS_PASSWORD:}
timeout: 2s
In Boot 3 the prefix is spring.data.redis; in Boot 2 it was spring.redis. If you copy from old articles, the setting will simply be ignored.
@Service
class OtpService {
private final StringRedisTemplate redis;
OtpService(StringRedisTemplate redis) { this.redis = redis; }
void save(String phone, String code) {
redis.opsForValue().set("otp:" + phone, code, Duration.ofMinutes(2));
}
}
For local testing, docker run -p 6379:6379 redis:7 is enough, and for tests Testcontainers is convenient.
Sign up to mark studied questions and save your progress.