如何在 Spring 中使用带有方法返回类型 Stream<Object> 的@Cacheable?

amj*_*jad 2 spring spring-data-jpa spring-boot java-stream

我有以下 JPA 方法来获取对象流

@Cacheable("accounts")
    Stream<Account> findAccounts(int branchCode, int accountCode);
Run Code Online (Sandbox Code Playgroud)

由于流将在调用该方法后关闭,因此当我第二次调用该方法时出现以下错误。

java.lang.IllegalStateException: stream has already been operated upon or closed
Run Code Online (Sandbox Code Playgroud)

我喜欢做的是;缓存流的内容,即帐户并从缓存中读取所有后续调用。实现这一目标的最佳方法是什么?

更新:请注意,我知道使用 List 但需要保留返回类型 Stream。

Tom*_*ski 6

您无法缓存Stream. 但是,您可以缓存的内容是任何类型的Collection(最好是List)。

为了不破坏 API 契约,您只需提取一个返回 a 的私有方法List,并用@Cacheable. 于是,原来的方法(不带@Cacheable注释)只是调用缓存的方法,并呼吁stream()其上,构建一个新的StreamList它被称为每一次,这样的:

Stream<Account> findAccounts(int branchCode, int accountCode) {
    return findAccountList(branchCode, accountCode).stream();
}

@Cacheable("accounts")
private List<Account> findAccountList(int branchCode, int accountCode);
Run Code Online (Sandbox Code Playgroud)

但是,如果您非常确定要缓存延迟评估的数据结构(我推荐),您可以使用jOO? 's SeqBuffer(不过,它是包私有的,所以我想您只需要复制代码即可)。

免责声明:我是该SeqBuffer课程的作者。