Spring Cache with collection of items/entities

前端 未结 2 788
北海茫月
北海茫月 2020-12-02 20:50

I am using Spring Cache, where I pass in a collection of keys, and the return is a list of entities. I would like to have the caching framework understand that each element

2条回答
  •  温柔的废话
    2020-12-02 21:35

    With @CachePut and a helper method you can achieve it very simply like this :

    public List getAllByCode(Listcodes) {
        return countryDao.findAllInCodes(codes);
    }
    
    public void preloadCache(Listcodes) {
        List allCountries = getAllByCode(codes);
        for (Country country : allCountries) {
            cacheCountry(country);
        }
    }
    
    @CachePut
    public Country cacheCountry(Country country) {
        return country;
    }
    

    Note

    This will only add values to the cache, but never remove old values. You can easily do cache eviction before you add new values

    Option 2

    There is a proposal to make it work like this :

    @CollectionCacheable
    public List getAllByCode(Listcodes) {    
    

    See :

    • https://github.com/spring-projects/spring-framework/issues/23221
    • https://github.com/neiser/spring-collection-cacheable

    If you are impatient take the code from GitHub and integrate locally

提交回复
热议问题