【问题标题】:How to use @Cacheable with method return type Stream<Object> in Spring?如何在 Spring 中将 @Cacheable 与方法返回类型 Stream<Object> 一起使用?
【发布时间】:2018-07-18 11:59:15
【问题描述】:

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

@Cacheable("accounts")
    Stream<Account> findAccounts(int branchCode, int accountCode);

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

java.lang.IllegalStateException: stream has already been operated upon or closed

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

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

【问题讨论】:

  • 缓存List&lt;Account&gt;而不是Stream可能吗?
  • 可行,但我不想破坏 API 合同。 IE。返回列表而不是流式传输
  • 让我知道我的回答是否对您有用(或者为什么没有用)。如果有,请accept it

标签: spring spring-boot spring-data-jpa java-stream


【解决方案1】:

您不能缓存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λ's @987654322 @(不过它是包私有的,所以我猜你只需要复制代码)。

免责声明:我是SeqBuffer 类的作者。

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2020-12-29
    • 2019-11-06
    • 2019-05-08
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多