@cacheput is not updating the existing cache

戏子无情 提交于 2021-02-07 14:15:05

问题


I am working with Spring 4 and Hazelcast 3.2. I am trying to add a new record to existing cache with below code. somehow cache is not getting updated and at the same time I don't see any errors also. below is the code snippet for reference.

Note:- Cacheable is working fine, only cacheput is not working. Please throw light on this

@SuppressWarnings("unchecked")`enter code here`
    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    @Cacheable(value="user-role-data")
    public List<User> getUsersList() {
    // Business Logic
    List<User> users= criteriaQuery.list();

    }

@SuppressWarnings("unchecked")
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    @CachePut(value = "user-role-data")
    public User addUser(User user) {
                    return user;

    } 

回答1:


I had the same issue and managed to solved it. The issue seemed to be tied to the transaction management. Bascially updating the cache in the same method where you are creating or updating the new record does not work because the transaction was not committed. Here's how I solved it.

Service layer calls repo to insert user Then go back to service layer After the insert /update db call In the service layer I called a refresh cache method That returned the user data and this method has the cacheput annotation After that it worked.




回答2:


An alternative approach is you could use @CacheEvict(allEntries = true) on the method used to Save or Update or Delete the records. It will flush the existing cache.

Example:

@CacheEvict(allEntries = true) 
public void saveOrUpdate(Person person) 
{
     personRepository.save(person);
}

A new cache will be formed with updated result the next time you call a @Cacheable method

Example:

@Cacheable // caches the result of getAllPersons() method
public List<Person> getAllPersons() 
{
     return personRepository.findAll();
}


来源:https://stackoverflow.com/questions/33155037/cacheput-is-not-updating-the-existing-cache

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!