V
V
Vladimir Kim2019-11-24 18:44:54
Java
Vladimir Kim, 2019-11-24 18:44:54

Spring @cachable not caching data?

@ResponseBody
    @Cacheable("sums")
    @PostMapping("/getAPlusB")
    public int getAPlusB(@RequestParam int A,
                            @RequestParam int B,
                            Model model) {
        int result = A + B;
        model.addAttribute("result", result);
        System.out.println("Cache isn't working!");
        return result;
    }
 
@Configuration
@EnableCaching
@EnableAutoConfiguration
public class CachingConfig {
 
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("sums");
    }
}

As a result, when I pass the same data (A = 10, B = 20) several times, the message "Cache isn't working" is displayed all the time. CachingConfig is in a different file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vest, 2019-12-29
@ETOZHEKIM

In short, it took a bit of fiddling to create a project that could reproduce your situation. In simple words, your cache is always empty because the third parameter of your function is constantly changing... Model .
Each time POST is called, a Model object is created and has a new address each time. Hence it turns out that this model cannot be found in the cache.
Your code can be fixed if you specify the caching key: I learned about the key format as usual from here . Perhaps you are wondering how I found this out? Again, I spent enough time on the project where I just debugged the spring code. Everything is simple through aspects. You are welcome.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question