skip to Main Content

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?

2

Answers


  1. 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 }")
    
    Login or Signup to reply.
  2. @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);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search