ZetCode

Spring Boot RouterFunction

最后修改于 2023 年 7 月 29 日

在本文中,我们将展示如何在 Spring Boot 应用程序中创建函数式路由。

响应式编程

响应式编程 是一种编程范式,它具有函数式、事件驱动、非阻塞、异步和围绕数据流处理的特点。 术语 响应式 来自于我们对变化的反应,例如鼠标点击或 I/O 事件。

传统的 Spring MVC 应用程序使用 @GetMapping 等注解将请求路径映射到控制器操作。 函数式路由 API 是这种映射的另一种方式。

RouterFunction

RouterFunction 代表一个路由到处理函数的功能。

Spring Boot RouterFunction 示例

在以下应用程序中,我们创建一个具有函数式路由的响应式 Spring Boot 应用程序。

build.gradle
...
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           └───routes
│   │                   MyRoutes.java
│   └───resources
└───test
    └───java
        └───com
            └───zetcode
                └───routes
                        MyRoutesTest.java

这是 Spring 应用程序的项目结构。

build.gradle
plugins {
    id 'org.springframework.boot' version '3.1.1'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.zetcode'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

这是 build.gradle 文件。 RouterFunctionspring-boot-starter-webflux 依赖项中。

com/zetcode/routes/MyRoutes.java
package com.zetcode.routes;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

@Configuration
public class MyRoutes {

    @Bean
    RouterFunction<ServerResponse> home() {
        return route(GET("/"), request -> ok().body(fromValue("Home page")));
    }

    @Bean
    RouterFunction<ServerResponse> about() {
        return route(GET("/about"), request -> ok().body(fromValue("About page")));
    }
}

我们定义了两个函数路由。

@Bean
RouterFunction<ServerResponse> home() {
    return route(GET("/"), request -> ok().body(fromValue("Home page")));
}

使用函数式路由,我们可以编写简单而优雅的代码。 在这里,我们为首页返回一个简单的文本消息。

com/zetcode/routes/MyRoutesTest.java
package com.zetcode.routes;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyRoutesTest {

    @Autowired
    private WebTestClient client;

    @Test
    public void test_home_page() {

        client.get().uri("/").exchange().expectStatus().isOk()
                .expectBody(String.class).isEqualTo("Home page");
    }

    @Test
    public void test_about_page() {

        client.get().uri("/about").exchange().expectStatus().isOk()
                .expectBody(String.class).isEqualTo("About page");
    }
}

使用 WebTestClient,我们测试这两个路由。

com/zetcode/Application.java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application  {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

此代码设置了 Spring Boot 应用程序。

$ ./gradlew bootRun

我们运行应用程序并导航到 localhost:8080

在本文中,我们学习了如何使用 RouterFunction 函数式路由。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 Spring Boot 教程