我有下面的JPA方法,它获取对象流
@Cacheable("accounts")
Stream<Account> findAccounts(int branchCode, int accountCode);
由于流将在调用该方法后关闭,因此当我第二次调用该方法时,会出现以下错误。
java.lang.IllegalStateException: stream has already been operated upon or closed
我喜欢做的是;缓存流的内容,即帐户,并从缓存中读取所有后续调用。实现这一目标的最佳方式是什么?
UPDATE:注意,我知道使用List,但需要保留返回类型Stream。
不能缓存Stream
。不过,您可以缓存的是任何类型的Collection
(最好是List
(。
为了不破坏API契约,您只需提取一个返回List
的私有方法,并使用@Cacheable
对其进行注释。然后,原始方法(没有@Cacheable
注释(只调用可缓存的方法并在其上调用stream()
,每次调用时都从List
构造一个新的Stream
,如下所示:
Stream<Account> findAccounts(int branchCode, int accountCode) {
return findAccountList(branchCode, accountCode).stream();
}
@Cacheable("accounts")
private List<Account> findAccountList(int branchCode, int accountCode);
但是,如果非常决心缓存一个延迟评估的数据结构(我不建议这样做(,您可以使用jOOλ的SeqBuffer
(不过它是包私有的,所以我想您只需要复制代码(。
免责声明:我是SeqBuffer
课程的作者。