【问题标题】:Using spring webflux to consume two apis one after another使用spring webflux一个接一个消费两个api
【发布时间】:2019-03-01 14:23:04
【问题描述】:

我需要编写一个新的 api,它将接受一些参数,使用和现有的 api,然后使用这个结果来使用第二个现有的 api。 我之前没有使用过 spring 5,但我注意到 rest 模板将被弃用,我应该使用 webflux。 我已经完成了一些关于简单案例的教程,但不知道如何解决我的具体问题。

鉴于我有以下两个 api:

@GetMapping("/foo/{id}")
public Foo getById(@PathVariable int id) {
    return new Foo(id, "foo");
}

@PostMapping("/bar")
public Bar createBar(@RequestBody Bar bar) {
    return bar;
}

我有一个包含新 api 的新 springboot 应用程序:

@SpringBootApplication
@RestController
public class ReactiveClientApplication {
    @Bean
    WebClient fooWebClient() {
        return WebClient.builder()
            .baseUrl("http://localhost:8080/foo")
            .build();
    }

    @Bean
    WebClient barWebClient() {
        return WebClient.builder()
            .baseUrl("http://localhost:8080/bar")
            .build();
    }

    // This works fine
    @PostMapping("/foo/{fooId}")
    public Mono<Foo> foo(@PathVariable Integer fooId) {
        return fooWebClient()
            .get()
            .uri("/{id}", fooId)
            .retrieve()
            .bodyToMono(Foo.class);
    }

    // This works fine
    @PostMapping("/bar")
    public Mono<Bar> bar() {
        return barWebClient()
            .post()
            .body(Mono.just(new Bar("bar", new Date())), Bar.class)
            .retrieve()
            .bodyToMono(Bar.class);
    }

    // I cannot get this to work
    @PostMapping("/foobar/{fooId}")
    public Mono<Bar> fooBar(@PathVariable Integer fooId) {
        Mono<Foo> fooMono = fooWebClient().get().uri("/{id}", fooId).retrieve().bodyToMono(Foo.class);
        fooMono.flatMap(foo -> {
            Mono<Bar> barMono = barWebClient().post().body(Mono.just(new Bar(foo.getFooStuff(), new Date())), Bar.class)
                    .retrieve().bodyToMono(Bar.class);
            return barMono;
        });
        return null;
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(ReactiveClientApplication.class)
            .properties(Collections.singletonMap("server.port", "8081"))
            .run(args);
    }
}

foobar方法需要调用并等待foo的响应,用this调用bar然后等待响应返回。

我认为我显然需要付出更多努力来了解这一切是如何运作的,但我希望有人能够指出我应该如何做到这一点的正确方向。

谢谢!

【问题讨论】:

  • 你能解释一下什么不起作用吗?你有例外吗?这是返回意外吗?

标签: spring-webflux


【解决方案1】:

您不应返回 null。下面的代码呢:

@PostMapping("/foobar/{fooId}")
public Mono<Bar> fooBar(@PathVariable Integer fooId) {
    Mono<Foo> fooMono = fooWebClient().get().uri("/{id}", fooId).retrieve().bodyToMono(Foo.class);
    return fooMono.flatMap(foo -> 
                 barWebClient()
                    .post()
                    .body(Mono.just(new Bar(foo.getFooStuff(), new Date())), Bar.class)
                    .retrieve()
                    .bodyToMono(Bar.class)
    );
}

【讨论】:

  • 谢谢。这正是我所需要的。
猜你喜欢
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 2015-05-28
相关资源
最近更新 更多