将 ResponseEntity 迁移到 Mono<ResponseEntity

Migration ResponseEntity to Mono<ResponseEntity

在 spring 引导应用程序中,我使用 webclient

调用 ms

ResponseEntity 响应 = webClient.post() .uri("/auth/login") .body(Mono.just(loginRequest), LoginDto.class) 。取回() .toEntity(LoginResponse.class) .block();

我接角色后,将其放入合集

Collection<? extends GrantedAuthority> authorities = response.getBody().getRoles().stream()
            .map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());

在我创建一个 return 一个 Mono

Mono.just(new UsernamePasswordAuthenticationToken(username, password, authorities));

我将 ms 修改为 return Mono 以真正响应

有了这个改变,我不知道要改变什么

Mono<ResponseEntity<LoginResponse>> response = webClient.post()
            .uri("/auth/login")
            .body(Mono.just(loginRequest), LoginDto.class)
            .retrieve()
            .toEntity(LoginResponse.class);

Collection<? extends GrantedAuthority> authorities = response.getBody().getRoles().stream()
            .map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());

Mono.just(new UsernamePasswordAuthenticationToken(username, password, authorities));

您使用 flatMap 以异步方式将某些内容映射到其他内容。

public Mono<UsernamePasswordAuthenticationToken> foobar() {
    Mono<ResponseEntity<LoginResponse>> response = webClient.post()
            .uri("/auth/login")
            .body(Mono.just(loginRequest), LoginDto.class)
            .retrieve()
            .toEntity(LoginResponse.class);

    return response.flatMap(response -> {
        Collection<? extends GrantedAuthority> authorities = response.getBody()
             .getRoles()
             .stream()
             .map(item -> new SimpleGrantedAuthority(item))
             .collect(Collectors.toList());
        return Mono.just(new UsernamePasswordAuthenticationToken(username, password, authorities));
    }
}