I am attempting to implement caching in my application using Ehcache and the Spring 3.1 built in caching annotations (@Cacheable, @CacheEvict, and @CachePut).
I have created a cache as follows:
@Cacheable(value = "userCache", key = "#user.id")
public List<User> getAllUsers() {
...
}
I am attempting to update this cache with a new value using the @CachePut annotation as below:
@CachePut(value = "userCache", key = "#user.id")
public void addUser(User user) {
...
}
However, the new "User" is not being added to the cache. Is this because of the void return type?
As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.
Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation.
Yes, it's because void return type. The @CachePut annotation places the result of method into the cache. In your case there is no result so nothing is put to the cache.
Change method signature to return User:
public User addUser(User user) {
...
}
This wont work , cause you are using same cache value "userCache" but return type of method getAllUsers is List and return type of addUser is User. which will create inconsistency in data that have been stored in cache.
( List + User ) : this type of data will be formed in cache.
And later when you will call method getAllUsers , code will be
List userList = getAllUsers();
But in this case , data will be fetched from cache and throw "Class cast Exception".
As , ( List + User ) can not be cast in to List.
Is there any solution to this? I am stuck with this and don't know how to proceed. Will using custom annotations work here?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With