首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 5 新特性:函數式 Web 框架(Spring WebFlux)核心組件與實戰示例

     編輯:Java 綜合教學

Spring 5 函數式 Web 框架實戰

示例:響應式 Person 儲存庫暴露為 HTTP 端點

public interface PersonRepository {
    Mono<Person> getPerson(int id);
    Flux<Person> allPeople();
    Mono<Void> savePerson(Mono<Person> person);
}

路由定義

RouterFunction<?> route = route(GET("/person/{id}"), request -> {
    Mono<Person> person = Mono.justOrEmpty(request.pathVariable("id"))
        .map(Integer::valueOf)
        .then(repository::getPerson);
    return Response.ok().body(fromPublisher(person, Person.class));
}).and(route(GET("/person"), request -> {
    Flux<Person> people = repository.allPeople();
    return Response.ok().body(fromPublisher(people, Person.class));
})).and(route(POST("/person"), request -> {
    Mono<Person> person = request.body(toMono(Person.class));
    return Response.ok().build(repository.savePerson(person));
}));

運行於 Reactor Netty

HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create("localhost", 8080);
server.startAndAwait(adapter);

測試

$ curl 'https://localhost:8080/person/1'
{"name":"John Doe","age":42}

核心組件詳解

HandlerFunction

類型:Function<Request, Response<T>>。無副作用,易測試、優化。構建響應使用 Response.ok().body(...)。

HandlerFunction<String> helloWorld = request -> Response.ok().body(fromObject("Hello World"));

RouterFunction

類型:Function<Request, Optional<HandlerFunction<T>>>。匹配請求並返回處理器。可用 RouterFunctions.route(predicate, handler) 簡化。

RouterFunction<String> route = route(GET("/hello"), handler::helloWorld)
    .and(route(GET("/answer"), handler::theAnswer));

支持謂詞組合:method(HttpMethod.GET).and(path("/hello"))。

FilterFunction

類型:BiFunction<Request, HandlerFunction<T>, Response<R>>。可攔截請求/響應,實現日誌、安全、緩存。

RouterFunction<?> route = route(GET("/hello"), handler::helloWorld)
    .filter((request, next) -> {
        System.out.println("Before: " + request.path());
        Response<?> resp = next.handle(request);
        System.out.println("After: " + resp.body());
        return resp;
    });

使用 andSame() 保持類型一致性,便於過濾器處理特定響應類型。

部署選項

  • Reactor Netty:HttpServer.create(...)
  • Tomcat (Servlet 3.1+):ServletHttpHandlerAdapter + Tomcat
  • Undertow、RxNetty 等

無需 Spring ApplicationContext 即可運行,組件可選注入上下文。

總結

  • HandlerFunction:處理請求返回響應
  • RouterFunction:路由匹配並可組合
  • FilterFunction:過濾鏈攔截
  • 可在多種響應式運行時部署
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved