deChristo
deChristo

Reputation: 1878

Java Spring Boot how to set Redis cache key for multiple query string parameters on controller

With the following Controller method:

    @GetMapping("/books")
    public ResponseEntity<List<Book>> getBooksByTitleOrAuthor(
        @RequestParam(required = false) String title,
        @RequestParam(required = false) String author) {

        if ((title== null || title.isEmpty()) && (author == null || author.isEmpty()))
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

        if (author != null) {
            Logger.info("GET /books?author=" + author);
            return bookService.getByAuthor(author)
        }

        Logger.info("GET /books?title=" + title);
        return bookService.getByTitle(title));
    }

I can call the endpoint with:

/books?title=SomeBookTitle

or

/books?author=SomeAuthor

How can I set the Redis key with either title or author here using @Cacheable?

Upvotes: 0

Views: 2540

Answers (2)

rudahvb
rudahvb

Reputation: 36

You may try to use the cache SpEL metadata such as the name of the method being invoked as follows:

@Cacheable(value = "books", key = "{ #root.methodName, #title, #author }")

Upvotes: 2

swayamraina
swayamraina

Reputation: 3158

@Cacheable (
    cacheManager = "books", 
    value= "books", 
    key = "'book'"
)


cacheManager : name of bean which handles cache requests

@Bean(name = "books")
public CacheManager booksCacheManager(){
    // template bean is actual redis handler
    return RedisConfigUtils.genericCacheManager(TimeUnit.MILLISECONDS.toSeconds(expiry), templateBean);
}


@Bean(name = "templateBean")
    RedisTemplate couponRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        Jackson2JsonRedisSerializer type = new Jackson2JsonRedisSerializer<ArrayList>(ArrayList.class){
            @Override
            protected JavaType getJavaType(Class<?> clazz){
                if (List.class.isAssignableFrom(clazz)) {
                    setObjectMapper(mapper);
                    return mapper.getTypeFactory().constructCollectionType(ArrayList.class, Test.class);
                } else {
                    return super.getJavaType(clazz);
                }
            }
        };
        return RedisConfigUtils.genericRedisTemplate(redisConnectionFactory, type);
    }

Upvotes: 0

Related Questions