【问题标题】:clean solution for header API versioning using Spring WebFlux?使用 Spring WebFlux 进行标头 API 版本控制的干净解决方案?
【发布时间】:2019-07-07 00:08:46
【问题描述】:

尝试使用 RouterFunction 在 Spring WebFlux 中使用 HTTP 标头进行 API 版本控制。

使用 Spring WebFlux RouterFunction 无法使用 @GetMapping(headers = "API-VERSION=1.0.0")注解。

我目前的尝试在我看来不是一个好的尝试。

public Mono<ServerResponse> heartBeat(ServerRequest request) {
    final String apiVersion = request.headers().header("API-Version").get(0);

    switch (apiVersion) {
        case "1.0.0":
            return heartBeatV1_0_0(request);
        case "1.0.1":
            return heartBeatV1_0_1(request);
        default:
            return heartBeatV1_0_0(request);
    }
}

有没有更好的办法?

【问题讨论】:

    标签: spring-webflux api-versioning


    【解决方案1】:

    我认为您的方式还可以,但如果您正在寻找其他方法,您可以使用RouterFunction 路由您的版本。像这样的:

    @Bean
    RouterFunction<ServerResponse> routerFunction() {
        return RouterFunctions
                .route(
                        GET("/your/path").and(headers(headers -> testVersion(headers, "1.0.0"))),
                        /* handler function 1.0.0 */)
                .andRoute(
                        GET("/your/path").and(headers(headers -> testVersion(headers, "1.0.1"))),
                        /* handler function 1.0.1 */);
    }
    
    private boolean testVersion(ServerRequest.Headers headers, String version) {
        return headers.header("API-Version")
                .stream()
                .anyMatch(headerValue -> Objects.equals(headerValue, version));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2010-09-18
      相关资源
      最近更新 更多