How to utilize Redis for caching in Spring Boot?
Using Redis as a cache in SpringBoot can be implemented by following these steps:
- Add the dependency: First, add the dependency of Spring Data Redis in the pom.xml file as shown below:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- Configure Redis connection: Set up the Redis connection in the application.properties or application.yml file as shown below:
spring.redis.host=localhost
spring.redis.port=6379
- To use Redis caching: add the @Cacheable annotation to the methods where caching is needed, as shown below:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Cacheable(value = "users", key = "#userId")
public User getUserById(Long userId) {
return userRepository.findById(userId).orElse(null);
}
}
In the example above, the @Cacheable annotation indicates that the method will use a cache named “users” with the cache key being userId. When the method is called, if the corresponding value already exists in the cache, it will be returned directly. Otherwise, the method body will be executed and the result will be stored in the cache.
By following the above steps, you can use Redis as a cache in Spring Boot. It is important to ensure that the Redis server is already running and properly connected to the Spring Boot application.