I've got next method in UserService:
@Cacheable(value = "user", key="#p0")
public User find(String user) {
return userRepository.findByUser(User);
}
It caches well. In other service I have:
@Transactional
public void updateToken(int id, String token) {
Group group = groupRepository.findOne(id);
group.getMembers().forEach(member -> {
member.getUser().setToken(token);
removeUserCacheByName(member.getUser().getName());
});
groupRepository.save(group);
}
@CacheEvict(value = "user", key="#p0")
public void removeUserCacheByName(String name) {
log.debug("Removing user cache by name {}.", name);
}
After updateToken method, cache does not clear.
What you're seeing is normal. You're calling removeUserCacheByName()
from within the Proxy object so the catching aspect doesn't execute. You have this behaviour explained in the documentation.
You can do some things to work around this:
1) Take the evict method (removeUserCacheByName
) to another bean, autowire it in updateToken()'s class, and call it.
2) An ugly but useful one, autowire the ApplicationContext, get the same object from it and call the method, e.g.:
public class UserService{
@Autowired
private ApplicationContext ac;
@Transactional
public void updateToken(int id, String token) {
Group group = groupRepository.findOne(id);
group.getMembers().forEach(member -> {
member.getUser().setToken(token);
UserService sameBean = ac.getBean(UserService.class);
sameBean.removeUserCacheByName(member.getUser().getName());
});
groupRepository.save(group);
}
@CacheEvict(value = "user", key="#p0")
public void removeUserCacheByName(String name) {
log.debug("Removing user cache by name {}.", name);
}
}