【问题标题】:How to solve the, calling for Mono<Token> then the result will be used to another Mono<Collection>, which will then return Mono<collection>?如何解决,调用 Mono<Token> 然后结果将用于另一个 Mono<Collection>,然后返回 Mono<collection>?
【发布时间】:2020-04-25 04:32:25
【问题描述】:

您好,我刚开始学习响应式编程

我这里有这段代码,我的流程应该是 我将调用 tokenRepository 来获取令牌,然后使用 token.getAccessToken() 作为 cardRepository.findAllCards() 上的参数

public class CardService {

    private final CardRepository cardRepository;
    private final TokenRepository tokenRepository;

    public CardService(CardRepositorycardRepository,
                       TokenRepository tokenRepository) {
        this.cardRepository = cardRepository;
        this.tokenRepository = tokenRepository;
    }

    public Mono<CardCollection> findAllCards(MultiValueMap<String, String> queryParams) {
        Mono<Token> token =tokenRepository.requestToken(); 

        // then I would like to use the token.getAccessToken
        return cardRepository.findAllCards(token.getAccessToken, queryParams); // Then this should return Mono<CardCollection>
    }
}

想知道这是否可行?

【问题讨论】:

  • 为什么你认为不是?您必须为这段代码提供更多信息。
  • @papaya 因为你需要订阅才能提取数据
  • cardRepository.findAllCards 返回什么?
  • @Shoshi 它返回 Mono

标签: java reactive-programming spring-webflux spring-mono


【解决方案1】:

虽然我不太确定这是否正确,但我找到了答案。

How to pass data down the reactive chain

这就是我对我的代码所做的。

public Mono<CardCollection> findAllCards(MultiValueMap<String, String> queryParams) {
  return tokenRepository.requestToken().flatMap(token -> {
      return cardRepository.findAllCards(token.getAccessToken(), queryParams);
  });
}

【讨论】:

  • 这是正确的,只要令牌存储库使用非阻塞数据库驱动程序或 restclient(如 webflux)来获取令牌。
  • 谢谢@ThomasAndolf,有什么优雅的方法可以做到这一点吗?如果这个特定方法的流量很大怎么办?
  • 看起来已经很优雅了,如果流量很大,你觉得有什么问题吗?
  • 注意如果 tokenRepository.requestToken() 返回 null 或空令牌会怎样
  • @ThomasAndolf 没什么,我只是认为还有另一种方法可以做事。感谢您验证我的答案,这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 2019-05-25
  • 2021-07-31
  • 1970-01-01
  • 2021-01-16
  • 2014-02-13
  • 1970-01-01
相关资源
最近更新 更多