Documentation

Caching REST Services with Redis

Brian Sam-Bodden
Author
Brian Sam-Bodden, Developer Advocate at Redis

Objectives#

Agenda#

  • The basics of Caching RESTful Services
  • How to configure the Spring Data Redis RedisCacheManager using RedisCacheConfiguration
  • How to use the @Cacheable annotation to mark a REST controller response as cacheable If you get stuck:
  • The progress made in this lesson is available on the redi2read github repository at https://github.com/redis-developer/redi2read/tree/course/milestone-9

Spring-Redis Caching Recipe#

  • Configure the Redis cache manager
  • Enable application-wide caching with the @EnableCaching annotation
@SpringBootApplication
@EnableCaching
public class Redi2readApplication {

  // ...

  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() //
        .prefixCacheNameWith(this.getClass().getPackageName() + ".") //
        .entryTtl(Duration.ofHours(1)) //
        .disableCachingNullValues();

    return RedisCacheManager.builder(connectionFactory) //
        .cacheDefaults(config) //
        .build();
  }

  // ...
}
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import java.time.Duration;

Using the @Cacheable annotation#

@GetMapping("/search")
@Cacheable("book-search")
public SearchResults<String,String> search(@RequestParam(name="q")String query) {
  RediSearchCommands<String, String> commands = searchConnection.sync();
  SearchResults<String, String> results = commands.search(searchIndexName, query);
  return results;
}
curl --location --request GET 'http://localhost:8080/api/books/search?q=java'