使用spring-cache收件箱缓存可变对象的最佳实践

时间:2017-02-10 23:47:51

标签: java spring caching

我在工作的地方经常使用SpringCache。 我们有很多看起来像这样的方法:

public class CitiesManager {

    /**
     * Get all cities, cached
     */
    @Cachable( CACHE_REGION_CITIES )
    public List<City> getCities() {
        return getCitiesTransactional();
    }

    /**
     * Gets all cities, cached
     * This method is splitted from getCities(), to spare the redundant Transaction when Cities are fetched from cache.
     */
    @Transactional
    private List<City> getCitiesTransactional() {
        return repository.getCities();
    }
}

效果很好。 问题是 - 城市是一个可变对象。 碰巧getCities()的调用者需要一个城市并对其进行更改,这会破坏缓存。

使用一个这样的缓存,我们的解决方案是创建一个只读接口,例如:

public interface ReadonlyCity {

    String getName();

    int getPopulation();
}

这很有效,但对于我们缓存的每个课程来说,这都是一件麻烦事。

我想做的是两个中的一个: 1.告诉SpringCache用一个使它们不可变的代理包装它缓存的对象。例如,通过使每个setFoo()方法抛出UnSupportedOperationException。我知道它不是气密的,但它对我来说已经足够了。 2.使SpringCache序列化并反序列化它返回的对象。

或者如果您有其他建议,我想听听。

0 个答案:

没有答案