Spring Webflux 后端处理前端请求的 4 种方式

Posted carl-zhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Webflux 后端处理前端请求的 4 种方式相关的知识,希望对你有一定的参考价值。

Spring Webflux 是一个无响应系统。它具有某些特性,使其成为低延迟、高吞吐量工作负载的理想选择。Project Reactor 和 Spring 组合一起工作,使开发人员能够构建响应性、弹性、弹性和消息驱动的企业级反应系统。

Spring组合提供了两个并行栈。一种是基于带有Spring MVC和Spring Data构造的Servlet API。另一种是完全响应式栈,它利用了Spring WebFlux和Spring Data的响应式存储库。在这两种情况下,Spring Security 都为您提供了对两个栈的本机支持。

开发人员从阻塞代码转向非阻塞代码的主要原因之一是效率。响应式代码用更少的资源做更多的工作。Project Reactor和Spring WebFlux让开发人员利用多核、下一代处理器来处理潜在的大量并发连接。使用响应式处理,您可以用更少的微服务实例满足更多的并发用户。

Spring Webflux 支持 4 种方式来处理前端的请求。

1、Spring MVC Controller

1.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.carlgodd.webflux</groupId>
    <artifactId>spring-webflux-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-webflux-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2 applicaiton.properties

spring.main.allow-bean-definition-overriding=true

1.3 启动类

@SpringBootApplication
public class SpringWebfluxDemoApplication 

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


1.4 实体类

@Data
public class Product 

    private Long id;

    private String name;

    private String desc;


1.5 Controller

@RestController
@RequestMapping("rest")
public class EchoController 

    @RequestMapping("echo")
    public Product hello() 
        Product product = new Product();
        product.setId(1L);
        product.setName("IPhone 13");
        product.setDesc("rest controller");
        return product;
    


1.6 postman 测试

2、Websocket

2.1 websocket 处理类

@Component
public class EchoWeSocketHandler implements WebSocketHandler 

    @Override
    public Mono<Void> handle(final WebSocketSession session) 
        return session.send(session.receive().map(
                msg -> session.textMessage("[websocket] 服务端回声 : " + msg.getPayloadAsText())
            )
        );
    


2.2 websocket 配置类

@Configuration
public class WebSocketConfiguration 

    @Bean
    public HandlerMapping webSocketMapping(EchoWeSocketHandler echoHandler) 
        final Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/websocket/echo", echoHandler);

        final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        mapping.setUrlMap(map);
        return mapping;
    

    @Bean
    public WebSocketHandlerAdapter webSocketHandlerAdapter() 
        return new WebSocketHandlerAdapter();
    


2.3 postman 测试

3、简单请求处理

3.1 WebHandler 处理类

@Component
public class EchoWebHandler implements WebHandler 

    @SneakyThrows
    @Override
    public Mono<Void> handle(ServerWebExchange exchange) 
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        ObjectMapper objectMapper = new ObjectMapper();
        Product product = new Product();
        product.setId(1L);
        product.setName("IPhone 13");
        product.setDesc("web handler");
        DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(product));
        return response.writeWith(Mono.fromSupplier(() -> wrap));
    


3.2 WebHandler 配置类

@Configuration
public class WebHandlerConfiguration 

    @Bean
    public HandlerMapping simpleWebHandlerMapping(final EchoWebHandler webHandler) 
        final Map<String, WebHandler> map = new HashMap<>();
        map.put("/web/echo", webHandler);

        final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        mapping.setUrlMap(map);
        return mapping;
    


3.3 postman 测试

4、Function Handler

4.1 Function Handler 处理类

@Component
public class EchoFunctionHandler 

    public Mono<ServerResponse> echo(ServerRequest request) 
        Product product = new Product();
        product.setId(1L);
        product.setName("IPhone 13");
        product.setDesc("function handler");
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(product));
    


4.2 Function Handler 配置类

@Configuration
public class FunctionHandlerConfiguration 

    @Bean
    public RouterFunction<ServerResponse> route(EchoFunctionHandler echoFunctionHandler) 
        return RouterFunctions
                .route(RequestPredicates.GET("/function/echo")
                        .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), echoFunctionHandler::echo);
    



4.3 postman 测试

参考文章:

以上是关于Spring Webflux 后端处理前端请求的 4 种方式的主要内容,如果未能解决你的问题,请参考以下文章

Spring Webflux 后端处理前端请求的 4 种方式

Spring Webflux 后端处理前端请求的 4 种方式

带有 Webflux 的 Spring Boot:请求的资源上不存在“Access-Control-Allow-Origin”标头

使用 Spring Webflux 返回元素列表

传统的Spring Web MVC如何像WebFlux一样异步处理请求?

将错误消息从 SSE (Webflux) Spring Boot 应用程序传递到 Angular 7 前端