Spring Boot WebFlux 2.1.7 Chinese translation of documents

1 Introduction

From the beginning to learn Netty rxjava, Rector, then java8 of CompletableFuture, deeply fascinated by reactive programming, which is different from traditional sequential programming, maybe in the future can open up a world in the world of programming it!

Then exposed to WebFlux framework, but also full of strong interest, like pondering about it, but since the Chinese data is too small, then the idea of ​​playing the English document, but the level of English is really anxious to catch, always look one, forget last sentence. Oh, or else we translate a sentence out of it, so read on smooth, by the way learners can benefit under later (thinking things look to be translated, is also a stick of power).

Translated word for word and did not go to tangle, sought to smooth semantics, there is misunderstanding of the place, but also pointed out the trouble we explore learning together. In addition, the paper also added some demo own practice.

Original link: https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/htmlsingle/#boot-features-webflux

github Exercise Demo: https://github.com/JMCuixy/webflux

tips: Translation is a double benefit to improve their English and study skills to do it!

2. WebFlux Profile

Spring WebFlux new response frame Spring 5.0 introduced distinguished Spring MVC, it does not depend Servlet API, it is completely non-blocking asynchronous, and is implemented based on the flow specification responsive Reactor.

Spring WebFlux has two forms: based configuration and comment on. Notes based implementation is very similar to SpringMVC model, as in the following examples:

@RestController
@RequestMapping("/users")
public class MyRestController {

    @GetMapping("/\{user}")
    public Mono<User> getUser(@PathVariable Long user) {
        // ...
    }

    @GetMapping("/\{user}/customers")
    public Flux<Customer> getUserCustomers(@PathVariable Long user) {
        // ...
    }

    @DeleteMapping("/\{user}")
    public Mono<User> deleteUser(@PathVariable Long user) {
        // ...
    }

}

Configuration based implementation, the routing and logic specific requests separated, as the following examples:

@Configuration
public class RoutingConfiguration {

    @Bean
    public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) {
        return route(GET("/\{user}").and(accept(APPLICATION_JSON)), userHandler::getUser)
                .andRoute(GET("/\{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers)
                .andRoute(DELETE("/\{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser);
    }

}

@Component
public class UserHandler {

    public Mono<ServerResponse> getUser(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> getUserCustomers(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> deleteUser(ServerRequest request) {
        // ...
    }
}

WebFlux is part of the Spring Framework, which is a reference document provides detailed information.

You can define any number of RouterFunction Bean, to route your were collated and analyzed. Of course, you can also set the priority (@Order annotations) for multiple RouterFunction.

WebFlux start a project, first of all, we need to spring-boot-starter-webflux module to introduce your project. It is worth noting that if you also introduces a spring-boot-starter-web and spring-boot-starter-webflux module can cause Spring Boot automatically configure Spring MVC, instead WebFlux. Because some of the Spring developers introduced spring-boot-starter-webflux, just to use its reactive programming (for this reason also no way out), although you can force your project configuration to WebFlux:

SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)

3. Automatic Configuration

Spring Boot automatically configured to Spring WebFlux provided basically suitable for most applications.

Automatic configuration provides the Spring Boot mainly to do the following two tasks:

  • HTTP codec configuration and HttpMessageWriter examples HttpMessageReader
  • Support static resource mapping, including support for WebJars resources

If you want to keep Spring Boot WebFlux auto-configuration feature, and you want to add additional WebFlux configuration items, you can customize the configuration @Configuration class, but do not add @EnableWebFlux comment.

If you want complete control WebFlux, you can define @Configuration configuration class, and add @EnableWebFlux. Annotation.

4. HttpMessageReaders and an HTTP codec HttpMessageWriters

Spring WebFlux use HttpMessageReader and HttpMessageWriter interface conversion HTTP requests and responses, can be obtained by their default configuration CodecConfigurer:

public interface CodecConfigurer {
    ...

    List<HttpMessageReader<?>> getReaders();

    List<HttpMessageWriter<?>> getWriters();
    ...
}

Spring Boot CodecCustomizer provides an interface that allows you to further customize codec () method which can be obtained by CodecConfigurer objects to customize, which can register new codec tool, or the existing tool replacement, etc. codec. As in the following examples:

import org.springframework.boot.web.codec.CodecCustomizer;

@Configuration
public class MyConfiguration {

    @Bean
    public CodecCustomizer myCodecCustomizer() {
        return codecConfigurer -> {
            // ...
        }
    }

}

5. static resources

Spring Boot from the default directory classpath (/ static, / public, / resources, / META-INF / resources) to load static resources, of course, you can implement custom configuration class and override addResourceHandlers WebFluxConfigurer ways to modify the default resource path :

@Configuration
public class MyWebFluxConfigurer implements WebFluxConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // do more
    }
}

Spring Boot default static resource mapping in the path / **, of course, you can adjust the default mapping by modifying spring.webflux.static-path-pattern attribute, for example, to map all resources / resources / ** path, can be achieved in the following ways:

spring.webflux.static-path-pattern=/resources/**

You can also customize the resource directory by setting spring.resources.static-locations attribute value, if you do this, the default welcome page detection will also switch to the resource directory you set. So, in your resources directory, as long as there is an index.html page, all applications will be your home page.

In addition to standard static resources described earlier, there is a special case, and that is webjars content. If the static resources are packaged into webjars format, then the path to access those resources becomes / webjars / **.

Tips: the Spring WebFlux application is not strictly dependent on Servlet API, you can not deploy them as a war file, do not use the src / main / webapp directory.

6. template engine

Spring WebFlux addition to providing REST web services, but also support rendering dynamic HTML content, Spring WebFlux support a range of template engines, including Thymeleaf, FreeMarker and Mustache.

Spring Boot provides support for automatic configuration of the following template engine:

When you use one of these template engine and choose the Spring Boot automatic configuration, you will need your template file in the src / main / resources / templates directory to find the Spring Boot.

7. Exception Handling

Spring Boot provides a WebExceptionHandler to handle all errors, WebExceptionHandler execution is often considered the last step in the processing chain, located just before WebFlux provide services. For the end of the machine, it is usually a JSON response, comprising an HTTP status code, error messages and the like; for the browser, it is usually a "whitelabel" HTML error page rendering the same error message. Of course, you can also provide custom HTML template to display an error message (we will discuss below).

First, customize this feature often involves use of existing mechanisms, but to replace or augment the wrong content, you can add ErrorAttributes type of Bean.

To change the error-handling behavior can be achieved ErrorWebExceptionHandler and register the type of bean definitions, but WebExceptionHandler level is very low. Spring Boot therefore also provides a convenient way that inherit AbstractErrorWebExceptionHandler, so that you can deal with by WebFlux wrong way, as in the following example (in this configuration thief complex, the proposal is still obediently it with the default configuration):

public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {

    // Define constructor here

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {

        return RouterFunctions
                .route(aPredicate, aHandler)
                .andRoute(anotherPredicate, anotherHandler);
    }

}

If you want for a given error code display HTML error pages custom error page you can add a file in the / error directory. Can be static HTML (static resource that is added to any folder), you can use a template to build, the file name should be the exact status code or series of masks.

For example, to map a 404 error code to a static HTML file, your folder structure is as follows:

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- public/
             +- error/
             |   +- 404.html
             +- <other public assets>

Mustache template to use as a 5xx error code mapping, your folder structure is as follows:

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- templates/
             +- error/
             |   +- 5xx.mustache
             +- <other templates>

8. Filter

Spring WebFlux WebFilter provides an interface for the HTTP request - in response to filter the routes found in the context of the application will be automatically used to filter the bean WebFilter each routing! The following is a simple authentication filter demo - not for token request parameter 401 returns an error:

@Component
public class CustomWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        if (queryParams == null || StringUtils.isEmpty(queryParams.getFirst("token"))) {
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("code", "401");
            resultMap.put("msg", "非法请求");
            byte[] datas = new byte[0];
            try {
                datas = new ObjectMapper().writeValueAsBytes(resultMap);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ServerHttpResponse response = exchange.getResponse();
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            ServerHttpResponse response = exchange.getResponse();
            //Manipulate the response in some way
        }));
    }
}

The filter can be set by implementing the Ordered interface or annotation @Order execution order (in ascending order of execution is executed, the higher the value is interpreted as a lower priority). Spring Boot auto-configuration functionality provides some built-in filters for you, their order of execution is as follows:

web Filter Order
MetricsWebFilter Ordered.HIGHEST_PRECEDENCE + 1
WebFilterChainProxy (Spring Security) -100
HttpTraceWebFilter Ordered.LOWEST_PRECEDENCE - 10

Guess you like

Origin www.cnblogs.com/jmcui/p/11775217.html