上一章我们提到过Mono 与 Flux,对于具体的介绍没说到,这一章我在这里简单介绍一下,既然提到Mono和Flux,那肯定得提到什么是响应式编程,什么是WebFlux。一、什么是响应式编程对于关于什么是响应编程,网上的说也很多,这里简单一句话介绍:响应式编程是基于异步和事件驱动的非阻塞程序,只是垂直通过在 JVM 内启动少量线程扩展,而不是水平通过集群扩展。二、Mono 与 FluxMono 和 Flux Reactor 是提供的两种响应式APIMono:实现发布者,并返回 0 或 1 个元素Flux:实现发布者,并返回 N 个元素三、什么是Spring WebfluxSpring Boot Webflux 就是基于 Reactor 实现的。Spring Boot 2.0 包括一个新的 spring-webflux 模块。该模块包含对响应式 HTTP 和 WebSocket 客户端的支持,以及对 REST,HTML 和 WebSocket 交互等程序的支持。一般来说,Spring MVC 用于同步处理,Spring Webflux 用于异步处理。Spring Boot Webflux 有两种编程模型实现,一种类似 Spring MVC 注解方式,另一种是使用其功能性端点方式。注解的会在第二篇文章讲到,下面快速入门用 Spring Webflux 功能性方式实现。在Spring官方有介绍,如图所示:四、Thymeleaf渲染HTML这里就不演示如何创建项目了,大家参考第一章,我们需要引入Thymeleaf框架,在pom文件中添加如下内容即可:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>引入Thymeleaf后我们需要做一些简单的配置,在application.properties文件中直接粘贴即可。主要是包括常用的编码、是否开启缓存等等。spring.thymeleaf.cache=truespring.thymeleaf.check-template=truespring.thymeleaf.check-template-location=truespring.thymeleaf.enabled=truespring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML5spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.servlet.content-type=text/htmlspring.thymeleaf.suffix=.html编写HTML,把文件放在resources/templates下<!DOCTYPE html><html lang=“zh-CN” xmlns:th=“http://www.w3.org/1999/xhtml"><head> <meta charset=“UTF-8”> <title>Title</title></head><body><h1>Hello <span th:text="${name}"></span></h1><h1>Now time <span th:text="${time}"></span></h1></body></html>编写Controllerpackage io.intodream.kotlin02.webimport org.springframework.stereotype.Controllerimport org.springframework.ui.Modelimport org.springframework.web.bind.annotation.GetMappingimport org.springframework.web.bind.annotation.RequestMappingimport reactor.core.publisher.Monoimport java.time.LocalDateTime/** * @description * * @author Jwenk * @copyright intoDream.io 筑梦科技 * @email xmsjgzs@163.com * @date 2019-03-24,18:24 */@RequestMapping("/webflux”)@Controllerclass IndexController { @GetMapping("/index") fun index(model : Model): Mono<String> { model.addAttribute(“name”, “Tom”) model.addAttribute(“time”, LocalDateTime.now()) return Mono.create{ monoSink -> monoSink.success(“index”)} }}启动项目,访问路径http://localhost:8080/webflux/index看到图片里面的内容则说明编写成功了,在Controller里面可以直接返回String,而不是Mono<String> ,但是 Mono 代表着我这个返回 View 也是回调的。