【问题标题】:You have to block on webflux to operate. Is there a way to operate without blocking?您必须阻止 webflux 才能运行。有没有不阻塞的操作方法?
【发布时间】:2021-08-12 07:09:22
【问题描述】:

工作

        WebClient webClient = WebClient.create("https://fcm.googleapis.com/fcm/send");

        return  webClient.post()
                .uri("")
                .header("Authorization", "key=test")
                .bodyValue("")
                .retrieve().bodyToMono(String.class).block();

不工作

        WebClient webClient = WebClient.create("https://fcm.googleapis.com/fcm/send");

        return  webClient.post()
                .uri("")
                .header("Authorization", "key=test")
                .bodyValue("")
                .retrieve();

如何更改我的代码? 我不想使用该块。

【问题讨论】:

  • 我们需要更多上下文,什么应用程序是纯 webflux 应用程序还是 web 应用程序。调用它的代码是什么样的?您阅读过 reactor 入门文档吗?
  • 这是一个调度器。
  • 请再次阅读我的评论,我问了几个问题this is a scheduler 不是我任何问题的答案。
  • 这是一个 Web 服务器,正在打开服务器上的调度程序。我不太明白是纯webflux应用还是web应用的意思。我用它作为服务器,但我不知道服务器属于哪个区域。我不是服务器开发人员,但我正在编写服务器代码,所以我不擅长基础知识。我没有老板,所以我没有人可以问。
  • 你调用的代码是``` @Scheduled(fixedDelay = 60000) public void init() throws Exception { try { ```

标签: spring-webflux webclient blocking


【解决方案1】:

Webflux 使用的是反应式编程范式。这与传统的命令式方法有很大不同。

一个很大的区别是在您订阅之前什么都不会发生

你应该这样处理它:


WebClient webClient = WebClient.create("https://fcm.googleapis.com/fcm/send");

        return  webClient.post()
                .uri("")
                .header("Authorization", "key=test")
                .bodyValue("")
                .retrieve()
                .bodyToMono(YourResponseObject.class)
                .flatMap(yourResponseObject -> dataRepository.save(yourSavedResponse))
                .subscribe(yourSavedResponse -> 
                                log.info("saved {} to database", yourSavedResponse(),
                                throwable -> log.error("an error occured", throwable));

您使用.block() 的代码示例之所以有效,是因为您对block() 的调用将整个sn-p 从被动代码变为阻塞代码。

【讨论】:

    猜你喜欢
    • 2013-06-18
    • 2013-07-05
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多