欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 前端技术 > javascript >内容正文

javascript

spring 5 新特性:函数式web框架 -凯发k8官方网

发布时间:2025/1/21 javascript 21 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 spring 5 新特性:函数式web框架 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘python工程师标准>>>

 正如juergen博客中所提到的,spring 5.0的第二个里程碑是引入了一个新的函数式web框架。在这篇文章中,我们将给出关于这个框架的更多信息。

 

我们先从示例应用程序的一些摘录开始。下面是暴露person对象的响应信息库。很类似于传统的,非响应信息库,只不过它返回flux而传统的返回list,以及返回mono的地方返回person。mono用作完成标识:指出何时保存被完成。关于reactor类型的更多信息,请参阅此博客文章。

public interface personrepository {mono getperson(int id);flux allpeople();mono saveperson(mono person); }

下面是我们如何暴露带有新的函数式web框架的资源库:

routerfunction route = route(get("/person/{id}"),request -> {mono 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 people = repository.allpeople();return response.ok().body(frompublisher(people, person.class));})).and(route(post("/person"),request -> {mono 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 'http://localhost:8080/person/2'
{"name":"john doe","age":42}

下面还有更多介绍!! !

 

我会通过彻底说明核心组件来介绍框架:handlerfunction,routerfunction,以及filterfunction。这三个接口以及文中描述的所有其他类型都可以在org.springframework.web.reactive.function包中找到。

handlerfunction

这一新框架的起点是handlerfunction,基本上是function>,其中request和response是新定义的,一成不变的界面友好地来提供jdk-8 dsl到底层http消息。对于构建response实体是一个方便的构建工具,非常类似于在responseentity中看到的。对应到handlerfunction注解是一个带有@requestmapping的方法。

下面是一个简单的“hello world”处理函数的例子,返回有200状态以及body为string的响应消息:

handlerfunction helloworld =request -> response.ok().body(fromobject("hello world"));

正如我们在上面的例子中看到的,处理函数是通过构建在reactor的基础上而完全响应:它们接受flux,mono,或任何其他相应的流publisher作为响应类型。

要注意的一点,handlerfunction本身是没有副作用的,因为它返回响应,而不是把它当作一个参数(参见servlet.service(servletrequest,servletresponse),这实质上是biconsumer )。没有副作用有很多好处:易于测试,编写和优化。

  • routerfunction

传入的请求被路由到有routerfunction的处理函数(即function>)路由到处理函数,如果它匹配的话;否则就返回一个空的结果。路由方法与@requestmapping注解的作用相似。但是,还有一个显著的区别:用注解时路由会被限制到注解的value所能表达的范围,处理这些方法的覆盖是困难的;当用路由方法的时候,代码就在那里,可以轻松的覆盖或替换。

下面是一个有内嵌处理函数的路由函数的例子。它看起来有点冗长,但不要担心:我们会找到办法让它变短。

routerfunction helloworldroute = request -> {if (request.path().equals("/hello-world")) {return optional.of(r -> response.ok().body(fromobject("hello world")));} else {return optional.empty();}};

一般不用写完整的路由方法,而是静态引入routerfunctions.route(),这样就可以用请求判断式(requestpredicate) (即 predicate)和处理方法(handlerfunction)创建路由方法了。如果判断式判断成功则返回处理方法,否则返回空结果。如下是用route方法方式重写上面的例子:

routerfunction helloworldroute =routerfunctions.route(request -> request.path().equals("/hello-world"),request -> response.ok().body(fromobject("hello world")));

你可以(静态地)导入requestpredicates.*以访问常用的谓词,基于路径、http方法、内容类型等等匹配。有了它,我们可以使helloworldroute更简单:

routerfunction helloworldroute =routerfunctions.route(requestpredicates.path("/hello-world"),request -> response.ok().body(fromobject("hello world")));

 

  • 组合函数

两个路由函数可以组成一个新的路由函数,路由到任一个处理函数:如果第一个函数不匹配,那么就执行第二个。你可以通过调用routerfunction.and(),像这样组合两个路由函数:

routerfunction route =route(path("/hello-world"),request -> response.ok().body(fromobject("hello world"))).and(route(path("/the-answer"),request -> response.ok().body(fromobject("42"))));

如果路径匹配/hello-world,以上将回应“hello world”,如果匹配/the-answer,则同时返回“42”。如果两者都不匹配,则返回一个空的optional。请注意,组合的路由函数会依次执行,因此在具体函数之前放入泛型函数是有意义的。

你也可以组合要求谓词,通过调用and或or。工作方式是这样:对于and,如果两个给定谓词匹配的话,结果谓词匹配,而如果两者中的一个谓语匹配的话,那么就or匹配。例如:

routerfunction route =route(method(httpmethod.get).and(path("/hello-world")), request -> response.ok().body(fromobject("hello world"))).and(route(method(httpmethod.get).and(path("/the-answer")), request -> response.ok().body(fromobject("42"))));

事实上,在requestpredicates发现的大多数谓词是组合的!例如,requestpredicates.get(string)是requestpredicates.method(httpmethod)和requestpredicates.path(string)的组合物。因此,我们可以将上面的代码重写为:

routerfunction route =route(get("/hello-world"),request -> response.ok().body(fromobject("hello world"))).and(route(get("/the-answer"),request -> response.ok().body(fromobject(42))));

 

  • 方法引用

顺便说一句:到目前为止,我们已经编写了所有的处理函数作为内联的lambda表达式。虽然这在演示和短的例子中表现良好,但是不得不说这有一种会导致“混乱”的倾向,因为你要混合两种担忧:请求路由和请求处理。因此,我们要看看是否能够让事情变得更简洁。首先,我们创建一个包含处理代码的类:

class demohandler {public response helloworld(request request) {return response.ok().body(fromobject("hello world"));}public response theanswer(request request) {return response.ok().body(fromobject("42"));} }

注意,两个方法都有一个兼容了处理函数的标志。这允许我们使用方法引用:

demohandler handler = new demohandler(); // or obtain via di routerfunction route =route(get("/hello-world"), handler::helloworld).and(route(get("/the-answer"), handler::theanswer));

 

  • filterfunction

由路由函数映射的路径可以通过调用routerfunction.filter(filterfunction)进行过滤,其中filterfunction本质上是bifunction, response>。函数的处理器(handler)参数代表的就是整个链条中的下一项: 这是一个典型的 handlerfunction, 但如果附加了多个过滤器的话,它也能够是另外的一个 filterfunction。让我们向路由添加一个日志过滤器:

routerfunction route =route(get("/hello-world"), handler::helloworld).and(route(get("/the-answer"), handler::theanswer)).filter((request, next) -> {system.out.println("before handler invocation: " request.path());response response = next.handle(request);object body = response.body();system.out.println("after handler invocation: " body);return response; });

需要注意的是,要不要调用下一个处理程序是可选的。这在安全和缓存方案中非常有用(如只在用户有足够权限的时候调用next)。

由于route是一个无限路由函数,因此我们知道接下来的处理程序会返回什么类型的响应信息。这就是为什么我们最终在我们的过滤器中用response结束以及用object响应body的原因。在处理程序类中,两种方法都返回response,所以应该有可能有string响应主体。我们可以通过使用routerfunction.andsame()来代替and()做到这一点。这种组合方法需要参数路由函数是相同的类型。例如,我们可以让所有的响应变成大写:

routerfunction route =route(get("/hello-world"), handler::helloworld).andsame(route(get("/the-answer"), handler::theanswer)).filter((request, next) -> {response response = next.handle(request);string newbody = response.body().touppercase();return response.from(response).body(fromobject(newbody));});

使用注解,相似的功能可以用@controlleradvice和/或servletfilter来实现。

 

所有这一切都很好,但有一件事忘了:我们如何才能在实际的http服务器中运行这些函数呢?答案勿庸置疑是通过调用另一个函数。你可以通过使用routerfunctions.tohttphandler()将路由函数转换成httphandler。httphandler是引进到spring 5.0 m1的一个响应抽象:它允许你运行在各种响应运行时上:reactor netty、rxnetty、servlet 3.1 ,和undertow。在这个例子中,我们已经表明了在reactor netty中运行route是怎么样的。对于tomcat,它看起来像这样:

httphandler httphandler = routerfunctions.tohttphandler(route); httpservlet servlet = new servlethttphandleradapter(httphandler); tomcat server = new tomcat(); context rootcontext = server.addcontext("",system.getproperty("java.io.tmpdir")); tomcat.addservlet(rootcontext, "servlet", servlet); rootcontext.addservletmapping("/", "servlet"); tomcatserver.start();

有一点要注意的是,上面的代码不依赖于spring应用程序上下文。就像jdbctemplate和其他spring实用工具类,使用应用程序上下文是可选的:你可以在上下文中接通处理程序和路由函数,但它不是必需的。

还要注意的是,你也可以转换路由函数为handlermapping,以便它可以在dispatcherhandler中运行(可能需要有响应的@controllers)。

 

让我通过简短的总结来得出结论:

  • 处理函数通过返回响应处理请求。
  • 路由函数路由到处理函数,并且可以与其他路由函数组合。
  • 路由函数可以通过过滤器进行过滤。
  • 路由函数可以在响应的web运行时中运行。

为了让大家能更全面的了解,我已经创建了一个使用泛函web框架的简单示例项目。你可以在github上找到这个项目。欢迎留下你的看法!

英文原文:new in spring 5: functional web framework

 

提示:spring-web-reactive的jar包比较新,如果找不到请点击这里自行下载。

转载于:https://my.oschina.net/mindfind/blog/782502

总结

以上是凯发k8官方网为你收集整理的spring 5 新特性:函数式web框架的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

网站地图