【问题标题】:Spring Cache -- ClassCastException (ehcache)Spring Cache -- ClassCastException (ehcache)
【发布时间】:2017-02-23 17:22:03
【问题描述】:

当我尝试从缓存中获取数据列表时遇到问题。

CategoryServiceImpl:

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
@Resource
private CategoryRepository categoryRepository;

@Override
@Caching(
        put = {
                @CachePut(value = "category", key = "'findByParrentId-' + #category.parentId + ',' + #category.user.userId"),
                @CachePut(value = "category", key = "'findAll-' + #category.user.userId")
        }
)
public Category add(Category category) {
    return categoryRepository.saveAndFlush(category);
}

@Override
@Cacheable(cacheNames = "category", key = "'findByParrentId-' + #prntId + ',' + #userId")
public List<Category> findByParentId(long prntId, long userId) {
    return categoryRepository.findByParentId(prntId, userId);
}

@Override
@Cacheable(cacheNames = "category", key = "'findAll-' + #userId")
public List<Category> findAll(long userId) {
    return categoryRepository.findAll(userId);
}
}

当我尝试获取类别列表时:

List<Category> categories = new ArrayList<>(categoryService.findByParentId(parentId, userSession.getUser().getUserId()));

我得到一个例外:

ClassCastException: ru.mrchebik.model.Category 无法转换为 java.util.List

完整的堆栈跟踪:http://pastebin.com/35A14ZW9

【问题讨论】:

    标签: java spring ehcache


    【解决方案1】:

    似乎名为“类别”的缓存被配置为保存类别元素:

    @CachePut(value = "category", key = "'findByParrentId-' + #category.parentId + ',' + #category.user.userId")
    

    然后你期望同样的缓存返回 List :

    @Cacheable(cacheNames = "category", key = "'findAll-' + #userId")
    

    我认为您希望缓存存储 List&lt;Category&gt; ;因此,当您尝试预热缓存时,不应放置 Category ,而应放置 List&lt;Category&gt;

    【讨论】:

    • 它有效,但我只给出一个元素。如果我想提供所有元素,我必须做什么?现在,我有了这个:public List&lt;Category&gt; add(Category category) { categoryRepository.saveAndFlush(category); List&lt;Category&gt; list = new ArrayList&lt;&gt;(); list.add(category); return list; } 我可以创建一个 List 的局部变量,但这不是缓存。
    【解决方案2】:

    您尝试实现的目标不适用于 Spring 缓存抽象。您必须手动完成更多操作才能获得想要的结果。

    首先,Spring 缓存现在可以表示需要将单个元素添加到缓存中的集合中。所以你需要自己维护映射的内容。

    使用当前声明,您不仅在缓存中有 Category 而不是 List&lt;Category&gt;,而且每个键只有最后一个 Category

    我建议删除@CachePut 注释并自己在缓存中更新集合。

    请注意,这需要是线程安全的,这可能需要更多考虑。

    【讨论】:

    • 谢谢,我使用@CacheEvictallEntries,我可以得到一个类别列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多