Spring Cache @Cacheable - not working while calling from another method of the same bean

后端 未结 9 1470
执念已碎
执念已碎 2020-11-27 10:06

Spring cache is not working when calling cached method from another method of the same bean.

Here is an example to explain my problem in clear way.<

9条回答
  •  春和景丽
    2020-11-27 10:59

    I use internal inner bean (FactoryInternalCache) with real cache for this purpose:

    @Component
    public class CacheableClientFactoryImpl implements ClientFactory {
    
    private final FactoryInternalCache factoryInternalCache;
    
    @Autowired
    public CacheableClientFactoryImpl(@Nonnull FactoryInternalCache factoryInternalCache) {
        this.factoryInternalCache = factoryInternalCache;
    }
    
    /**
     * Returns cached client instance from cache.
     */
    @Override
    public Client createClient(@Nonnull AggregatedConfig aggregateConfig) {
        return factoryInternalCache.createClient(aggregateConfig.getClientConfig());
    }
    
    /**
     * Returns cached client instance from cache.
     */
    @Override
    public Client createClient(@Nonnull ClientConfig clientConfig) {
        return factoryInternalCache.createClient(clientConfig);
    }
    
    /**
     * Spring caching feature works over AOP proxies, thus internal calls to cached methods don't work. That's why
     * this internal bean is created: it "proxifies" overloaded {@code #createClient(...)} methods
     * to real AOP proxified cacheable bean method {@link #createClient}.
     *
     * @see Spring Cache @Cacheable - not working while calling from another method of the same bean
     * @see Spring cache @Cacheable method ignored when called from within the same class
     */
    @EnableCaching
    @CacheConfig(cacheNames = "ClientFactoryCache")
    static class FactoryInternalCache {
    
        @Cacheable(sync = true)
        public Client createClient(@Nonnull ClientConfig clientConfig) {
            return ClientCreationUtils.createClient(clientConfig);
        }
    }
    }
    

提交回复
热议问题