skip to Main Content

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


  1. 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.

    class ProductService {
      
      private List<Product> productCache;
    
      public List<Product> findAll() {
        if (productCache == null) {
          productCache = productRepository.findAll();
        }
        return productCache;
      }
    }
    
    Login or Signup to reply.
  2. To fill your product cache with your List<Product> from the repository you could invoke the CacheManager programmatically:

    @Autowired CacheManager cacheManager;
    
    public List<Product> findAll() {
        List<Product> products = productRepository.findAll();
        for (Product product : products) {
            cacheManager.getCache("product").put(product.getProductId(), product);
        }
        return products;
    }
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search