如何从@PathVariable获得Mono而不阻塞

时间:2019-05-16 14:13:00

标签: spring spring-boot spring-webflux project-reactor

嗨,我想知道如何在我的控制器中拥有从两个参数到DTO类的Mono的任何阻塞代码转换。

假设我有如下所示的控制器:

@RestController
@RequiredArgsConstructor
class GithubRepositoryEndpoint {

    private final GithubService githubService;

    @GetMapping("/repositories/{owner}/{repositoryName}")
    Mono<RepoDetailsResponseDTO> getRepositoryDetails(@PathVariable("owner") String owner,
                                                      @PathVariable("repositoryName") String repositoryName) {
        return githubService.getRepositoryDetails(Mono.just(new RepoDetailsRequestDTO(owner, repositoryName)));
    }
}

我认为这条线正在阻塞: Mono.just(新RepoDetailsRequestDTO(所有者,repositoryName)

这是DTO类:


@Data
@Builder
@AllArgsConstructor
public class RepoDetailsRequestDTO {
    private String owner;
    private String repositoryName;
}

我的服务未阻止:

@Slf4j
@RequiredArgsConstructor
public class GithubService {

    private final GithubClient githubClient;
    private final RequestValidator requestValidator;
    private final DomainMapper domainMapper;

    public Mono<RepoDetailsResponseDTO> getRepositoryDetails(Mono<RepoDetailsRequestDTO> request) {
        return request.map(requestValidator::validate)
                .map(domainMapper::mapFromDto)
                .flatMap(ownerAndRepoName -> githubClient.fetchRepositoryDetails(ownerAndRepoName._1, ownerAndRepoName._2))
                .onErrorResume(exc -> Mono.error(new FetchRepoDetailsException(exc.getMessage(), exc)));
    }


}

1 个答案:

答案 0 :(得分:1)

线

Mono.just(new RepoDetailsRequestDTO(owner, repositoryName))

没有阻止。这只是一个构造函数调用。它不使用任何阻止API(例如io / file / network)。参数 owner repositoryName 都可以安全访问,因为它们已经包含解析的路径变量。