Update:
tried key="#p0"
, does not work
Trying to implement Redis with spring boot to cache my products, but I faced the problem, appreciate for any help
java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?)
Controller
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
ProductService productService;
@GetMapping("/")
public ResponseEntity<?> getAll() {
List<Product> products = productService.findAll();
return ResponseEntity.ok(products);
}
}
Service
@Cacheable(value = "product", key = "#productId")
public List<Product> findAll() {
return productRepository.findAll();
}
@EnableCaching annotation has also been put in the main class
3
Answers
The value of
key
should match the name of one of the arguments to the method annotated with@Cacheable
, findAll. As findAll has no arguments there is nothing to use as a key.https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/cache.html#cache-annotations-cacheable-key
A simple way to "cache" all the products in memory is just to store the result from the first call to
productRepository.findAll()
in an instance variable.To fill your
product
cache with yourList<Product>
from the repository you could invoke theCacheManager
programmatically:The value in key has to be one of the parameters of the method on which you’ve used the cacheable annotation.
One you thing you can do is to pass the value of productId when calling the findAll method.
The error simply means you’re using a null value as your key. Redis doesn’t allow this