簡體   English   中英

Spring Cache — ClassCastException(ehcache)

[英]Spring Cache — ClassCastException (ehcache)

我嘗試從緩存中獲取數據列表時遇到問題。

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

似乎將名為“ category”的緩存配置為容納Category元素:

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

然后您希望該緩存返回List:

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

我認為您希望緩存存儲List<Category> ; 因此,當您嘗試熱身緩存時,應該放置List<Category>而不是放置Category。

您要實現的目標不適用於Spring緩存抽象。 您必須手動執行更多操作才能獲得所需的結果。

首先,Spring緩存現在有一種方法可以表示需要將單個元素添加到緩存中的集合。 因此,您需要自己維護映射的內容。

使用當前聲明,不僅在緩存中有一個Category而不是List<Category>而且每個鍵只有最后一個Category

我建議刪除@CachePut批注並自己在緩存中進行集合更新。

請注意,這將是線程安全的,可能需要更多考慮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM