简体   繁体   中英

Ehcache Java Spring MVC and pagination @Cacheable

I use Ehcache 2.9.0 In my Spring Application and I would like to be able to cache a result based on the pagination.

First is how I use Ehcache right now:

@Cacheable(value ="EmployeesByCompanyId", key="#companyId")    
public List<Employee> getEmployeesByCompanyId(String companyId) throws Exception {
        return employeeRepository.getEmployeesByCompanyId(companyId);
}

@CacheEvict(value ="EmployeesByCompanyId", key="#company.id")
public Employee createNewEmployee(Employee employee, Company company)
{ ... }

Now is how I would like to use it for the same purpose but with a pagination. Example (not correct but it's the idea):

@Cacheable(value ="EmployeesByCompanyId", key="#companyId#page#maxResult"})    
@Override
public List<Employee> getEmployeesByCompanyId(String companyId, int page, int maxResult) throws Exception {
            return employeeRepository.getEmployeesByCompanyId(companyId, page, maxResult);
        }

Then when I had a new employee to the list it should Evict the cache but I would like to evict the cache related to a companyId. If I write something like that would it remove the cache related to the companyId:

@CacheEvict(value ="EmployeesByCompanyId", key="#companyId")

How should I do to make the caching work with the pagination and evict the cache related to the companyId when I add a new employee to this company?

Here a possible solution based on our comments.

Get the native EhCache object (as the Cache interface from Spring doesn't support getKeys method) from the cache manager

@Autowired private CacheManager cacheManager;
...
EhCache cache = (EhCache) cacheManager.getCache("EmployeesByCompanyId").getNativeCache();

Then you can iterate the cache keys, get the ones starting with companyId and remove them from the cache

for (Object key: cache.getKeys()) {
  if((String)key.startsWith(companyId))
    cache.remove(key);
}

See http://ehcache.org/apidocs/2.8.4/net/sf/ehcache/Ehcache.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM