This post will focus on integrating the Redis with the Spring Boot application to leverage the declarative annotation based caching support provided by the Spring cache abstraction.
2. Add Redis dependency to the application
Start by adding the Redis dependency to the build script file - build.gradle
Jedis is one of the popular Redis Java client, configure the JedisConnectionFactory which will create Jedis instances for connecting to the Redis server.
3.2 RedisTemplate
Create a RedisTemplate instance which helps to serialize/deserialize between the object and binary data on the Redis store.
Here StringRedisSerializer is used for serializing the key and GenericJackson2JsonRedisSerializer for the value. This template is a generified one, it can be wired to multiple components and reused as it’s thread-safe.
3.3 RedisCacheManager
The cache abstraction does not provide an actual store and relies on abstraction materialized by the org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces.
RedisCacheManager is the implimentation of the CacheManager for Redis.
4. Annotating the methods
For caching declaration, the abstraction provides a set of Java annotations:
4.1 @Cacheable
Triggers cache population
4.2 @CachePut
Updates the cache without interfering with the method execution
4.3 @CacheEvict
Triggers cache eviction
5. Conclusion
Redis is not a simple key-value store, it can be called as a data structure store as it’s can store data in advanced data structures. Spring Cache abstraction is a high level abstraction for interacting with the store.