java - Spring 5 : Web Reactive 的真实 Controller 示例

标签 java spring spring-mvc spring-webflux

我想使用 Spring 参与响应式(Reactive)编程世界。据我了解,it gives me a choice between two different paradigms : 基于注释的(我们熟知的 @Controller , @RequestMapping )和响应式(Reactive)的( which is intended to resolve an "Annotation Hell" )。

我的问题是不了解典型的响应式 Controller 的外观。我可以在我的 Controller 类中使用三个概念接口(interface):

HandlerFunction<T> (1) - 我为每个特定的 ServerRequest 定义一个方法 它返回一个具体的 HandlerFunction<T>例如,然后用路由器注册这些方法。对吧?

RouterFunction (2) 和 FilterFunction (3) - 是否有一个特定的地方所有RequestPredicate s 对应HandlerFunction s应该放在哪里?或者我可以在每个 Controller 中单独进行(就像我以前使用注释方法所做的那样)吗?如果是这样,那么如何通知全局处理程序(路由器,如果有的话?)从这个 Controller 应用这个路由器部分?

这就是我现在对响应式(Reactive) Controller "template"的看法:

public class Controller {
    // handlers
    private HandlerFunction<ServerResponse> handleA() {
        return request -> ok().body(fromObject("a"));
    }

    // router
    public RouterFunction<?> getRouter() {
        return route(GET("/a"), handleA()).and(
               route(GET("/b"), handleB()));
    }

    // filter
    public RouterFunction<?> getFilter() {
        return route(GET("/c"), handleC()).filter((request, next) -> next.handle(request));
    }
}

最后,如何在不使用注解的情况下说它是一个 Controller ?

我已经阅读了 Spring 引用资料以及官方博客上与此问题相关的所有帖子。有很多示例,但所有示例都是断章取义的(恕我直言),我无法将它们组合成完整的图片。

如果您能提供有关如何组织这些功能之间的交互的真实示例和良好实践,我将不胜感激。

最佳答案

这不是真实世界的例子,但到目前为止我是如何看待这方面的某种组织的:

https://github.com/LearningByExample/reactive-ms-example

关于java - Spring 5 : Web Reactive 的真实 Controller 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476795/

相关文章:

java - 一个 Controller 方法中的 Bean

jakarta-ee - Web 项目中的 ClassNotFoundException

Java - 多个 url 模式且无扩展名

java - BufferingResponseListener 和 getContentAsString 追加之前获取的内容

java - 检测桌面应用程序中的用户不活动

java - Tableau 服务器错误 : Unexpected end of file from server

java - Java Web 框架真的值得这么麻烦吗?

java - 无法使用 Spring Batch 框架连接到 Oracle 数据源

mysql - Spring Boot : Communications link failure after some hours of inactivity with Hibernate, JDBC 和 MySQL

java - 更改区域设置操作会导致 404