This commit is contained in:
周伟
2022-05-11 19:04:14 +08:00
parent 9440ac7291
commit d9c5ffd627
826 changed files with 0 additions and 481675 deletions

View File

@@ -1,868 +1,434 @@
<!DOCTYPE html>
<!-- saved from url=(0046)https://kaiiiz.github.io/hexo-theme-book-demo/ -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
<link rel="icon" href="/static/favicon.png">
<title>02 WebFlux 快速入门实践.md.html</title>
<!-- Spectre.css framework -->
<link rel="stylesheet" href="/static/index.css">
<!-- theme css & js -->
<meta name="generator" content="Hexo 4.2.0">
</head>
<body>
<div class="book-container">
<div class="book-sidebar">
<div class="book-brand">
<a href="/">
<img src="/static/favicon.png">
<span>技术文章摘抄</span>
</a>
</div>
<div class="book-menu uncollapsible">
<ul class="uncollapsible">
<li><a href="/" class="current-tab">首页</a></li>
</ul>
<ul class="uncollapsible">
<li><a href="../">上一级</a></li>
</ul>
<ul class="uncollapsible">
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/01 导读:课程概要.md.html">01 导读:课程概要.md.html</a>
</li>
<li>
<a class="current-tab" href="/专栏/案例上手 Spring Boot WebFlux/02 WebFlux 快速入门实践.md.html">02 WebFlux 快速入门实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/03 WebFlux Web CRUD 实践.md.html">03 WebFlux Web CRUD 实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/04 WebFlux 整合 MongoDB.md.html">04 WebFlux 整合 MongoDB.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/05 WebFlux 整合 Thymeleaf.md.html">05 WebFlux 整合 Thymeleaf.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html">06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/07 WebFlux 整合 Redis.md.html">07 WebFlux 整合 Redis.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/08 WebFlux 中 Redis 实现缓存.md.html">08 WebFlux 中 Redis 实现缓存.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/09 WebFlux 中 WebSocket 实现通信.md.html">09 WebFlux 中 WebSocket 实现通信.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/10 WebFlux 集成测试及部署.md.html">10 WebFlux 集成测试及部署.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/11 WebFlux 实战图书管理系统.md.html">11 WebFlux 实战图书管理系统.md.html</a>
</li>
</ul>
</div>
</div>
<div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
<div class="sidebar-toggle-inner"></div>
</div>
<script>
function add_inner() {
let inner = document.querySelector('.sidebar-toggle-inner')
inner.classList.add('show')
}
function remove_inner() {
let inner = document.querySelector('.sidebar-toggle-inner')
inner.classList.remove('show')
}
function sidebar_toggle() {
let sidebar_toggle = document.querySelector('.sidebar-toggle')
let sidebar = document.querySelector('.book-sidebar')
let content = document.querySelector('.off-canvas-content')
if (sidebar_toggle.classList.contains('extend')) { // show
sidebar_toggle.classList.remove('extend')
sidebar.classList.remove('hide')
content.classList.remove('extend')
} else { // hide
sidebar_toggle.classList.add('extend')
sidebar.classList.add('hide')
content.classList.add('extend')
}
}
function open_sidebar() {
let sidebar = document.querySelector('.book-sidebar')
let overlay = document.querySelector('.off-canvas-overlay')
sidebar.classList.add('show')
overlay.classList.add('show')
}
function hide_canvas() {
let sidebar = document.querySelector('.book-sidebar')
let overlay = document.querySelector('.off-canvas-overlay')
sidebar.classList.remove('show')
overlay.classList.remove('show')
}
</script>
<div class="off-canvas-content">
<div class="columns">
<div class="column col-12 col-lg-12">
<div class="book-navbar">
<!-- For Responsive Layout -->
<header class="navbar">
<section class="navbar-section">
<a onclick="open_sidebar()">
<i class="icon icon-menu"></i>
</a>
</section>
</header>
</div>
<div class="book-content" style="max-width: 960px; margin: 0 auto;
overflow-x: auto;
overflow-y: hidden;">
<div class="book-post">
<p id="tip" align="center"></p>
<div><h1>02 WebFlux 快速入门实践</h1>
<h3>Spring Boot 2.0</h3>
<p>spring.io 官网有句醒目的话是:</p>
<pre><code>BUILD ANYTHING WITH SPRING BOOT
</code></pre>
<p>Spring Boot Boot 顾名思义,是引导的意思)框架是用于简化 Spring 应用从搭建到开发的过程。应用开箱即用,只要通过一个指令,包括命令行 <code>java -jar</code><code>SpringApplication</code> 应用启动类 、 Spring Boot Maven 插件等就可以启动应用了。另外Spring Boot 强调只需要很少的配置文件,所以在开发生产级 Spring 应用中让开发变得更加高效和简易。目前Spring Boot 版本是 2.x 版本。Spring Boot 包括 WebFlux。</p>
<p><img src="assets/87db53c0-b936-11e7-b969-cb3cfaf54002-1608971096373" alt="img" /></p>
<h3>Spring Boot 2.0 WebFlux</h3>
<p>了解 WebFlux首先了解下什么是 Reactive Streams。Reactive Streams 是 JVM 中面向流的库标准和规范:</p>
<ul>
<li>处理可能无限数量的元素</li>
<li>按顺序处理</li>
<li>组件之间异步传递</li>
<li>强制性非阻塞背压Backpressure</li>
</ul>
<p><strong>Backpressure背压</strong></p>
<p>背压是一种常用策略,使得发布者拥有无限制的缓冲区存储元素,用于确保发布者发布元素太快时,不会去压制订阅者。</p>
<p><strong>Reactive Streams响应式流</strong></p>
<p>一般由以下组成:</p>
<ul>
<li>发布者:发布元素到订阅者</li>
<li>订阅者:消费元素</li>
<li>订阅:在发布者中,订阅被创建时,将与订阅者共享</li>
<li>处理器:发布者与订阅者之间处理数据</li>
</ul>
<p><strong>响应式编程</strong></p>
<p>有了 Reactive Streams 这种标准和规范,利用规范可以进行响应式编程。那再了解下什么是 Reactive programming 响应式编程。响应式编程是基于异步和事件驱动的非阻塞程序,只是垂直通过在 JVM 内启动少量线程扩展,而不是水平通过集群扩展。这就是一个编程范例,具体项目中如何体现呢?</p>
<p>响应式项目编程实战中,通过基于 Reactive Streams 规范实现的框架 Reactor 去实战。Reactor 一般提供两种响应式 API </p>
<ul>
<li>Mono实现发布者并返回 0 或 1 个元素</li>
<li>Flux实现发布者并返回 N 个元素</li>
</ul>
<p><strong>Spring Webflux</strong></p>
<p>Spring Boot Webflux 就是基于 Reactor 实现的。Spring Boot 2.0 包括一个新的 spring-webflux 模块。该模块包含对响应式 HTTP 和 WebSocket 客户端的支持,以及对 RESTHTML 和 WebSocket 交互等程序的支持。一般来说Spring MVC 用于同步处理Spring Webflux 用于异步处理。</p>
<p>Spring Boot Webflux 有两种编程模型实现,一种类似 Spring MVC 注解方式,另一种是使用其功能性端点方式。注解的会在第二篇文章讲到,下面快速入门用 Spring Webflux 功能性方式实现。</p>
<h3>Spring Boot 2.0 WebFlux 特性</h3>
<p>常用的 Spring Boot 2.0 WebFlux 生产的特性如下:</p>
<ul>
<li>响应式 API</li>
<li>编程模型</li>
<li>适用性</li>
<li>内嵌容器</li>
<li>Starter 组件</li>
</ul>
<p>还有对日志、Web、消息、测试及扩展等支持。</p>
<h4>响应式 API</h4>
<p>Reactor 框架是 Spring Boot Webflux 响应库依赖,通过 Reactive Streams 并与其他响应库交互。提供了 两种响应式 APIMono 和 Flux。一般是将 Publisher 作为输入,在框架内部转换成 Reactor 类型并处理逻辑,然后返回 Flux 或 Mono 作为输出。</p>
<h4>适用性</h4>
<p><img src="assets/e39654d047bd43a8f708d67f947c00c01523267.png" alt="file" /></p>
<p>一图就很明确了WebFlux 和 MVC 有交集,方便大家迁移。但是注意:</p>
<ul>
<li>MVC 能满足场景的,就不需要更改为 WebFlux。</li>
<li>要注意容器的支持,可以看看下面内嵌容器的支持。</li>
<li>微服务体系结构WebFlux 和 MVC 可以混合使用。尤其开发 IO 密集型服务的时候,选择 WebFlux 去实现。</li>
</ul>
<h4>编程模型</h4>
<p>Spring 5 web 模块包含了 Spring WebFlux 的 HTTP 抽象。类似 Servlet API , WebFlux 提供了 WebHandler API 去定义非阻塞 API 抽象接口。可以选择以下两种编程模型实现:</p>
<ul>
<li>注解控制层。和 MVC 保持一致WebFlux 也支持响应性 @RequestBody 注解。</li>
<li>功能性端点。基于 lambda 轻量级编程模型,用来路由和处理请求的小工具。和上面最大的区别就是,这种模型,全程控制了请求 - 响应的生命流程</li>
</ul>
<h4>内嵌容器</h4>
<p>跟 Spring Boot 大框架一样启动应用,但 WebFlux 默认是通过 Netty 启动,并且自动设置了默认端口为 8080。另外还提供了对 Jetty、Undertow 等容器的支持。开发者自行在添加对应的容器 Starter 组件依赖,即可配置并使用对应内嵌容器实例。</p>
<p>但是要注意,必须是 Servlet 3.1+ 容器,如 Tomcat、Jetty或者非 Servlet 容器,如 Netty 和 Undertow。</p>
<h4>Starter 组件</h4>
<p>跟 Spring Boot 大框架一样Spring Boot Webflux 提供了很多 “开箱即用” 的 Starter 组件。Starter 组件是可被加载在应用中的 Maven 依赖项。只需要在 Maven 配置中添加对应的依赖配置,即可使用对应的 Starter 组件。例如,添加 <code>spring-boot-starter-webflux</code> 依赖,就可用于构建响应式 API 服务,其包含了 Web Flux 和 Tomcat 内嵌容器等。</p>
<p>开发中,很多功能是通过添加 Starter 组件的方式来进行实现。那么Spring Boot 2.x 常用的 Starter 组件有哪些呢?</p>
<h3>Spring Boot 2.0 WebFlux 组件</h3>
<p>Spring Boot WebFlux 官方提供了很多 Starter 组件,每个模块会有多种技术实现选型支持,来实现各种复杂的业务需求:</p>
<ul>
<li>WebSpring WebFlux</li>
<li>模板引擎Thymeleaf</li>
<li>存储Redis、MongoDB、Cassandra不支持 MySQL</li>
<li>内嵌容器Tomcat、Jetty、Undertow</li>
</ul>
<h3>Spring Initializr 快速构建项目骨架</h3>
<p>Spring Boot Maven 工程,就是普通的 Maven 工程,加入了对应的 Spring Boot 依赖即可。Spring Initializr 则是像代码生成器一样,自动就给你出来了一个 Spring Boot Maven 工程。Spring Initializr 有两种方式可以得到 Spring Boot Maven 骨架工程:</p>
<h4>start.spring.io 在线生成</h4>
<p>Spring 官方提供了名为 Spring Initializr 的网站,去引导你快速生成 Spring Boot 应用。网站地址,<a href="https://start.spring.io/">详见这里</a>,操作步骤如下:</p>
<p>第一步,选择 Maven 或者 Gradle 构建工具,开发语言 Java 、Kotlin 或者 Groovy最后确定 Spring Boot 版本号。这里默认选择 Maven 构建工具、Java 开发语言和 Spring Boot 2.0.1。</p>
<p>第二步,输入 Maven 工程信息,即项目组 groupId 和名字 artifactId这里对应 Maven 信息为:</p>
<ul>
<li>groupIdspringboot</li>
<li>artifactIdsspringboot-webflux-1-quickstart</li>
</ul>
<p>这里默认版本号 version 为 0.0.1-SNAPSHOT三个属性在 Maven 依赖仓库是唯一标识的。</p>
<p>第三步,选择工程需要的 Starter 组件和其他依赖,最后单击“生成”按钮,即可获得骨架工程压缩包,这里快速入门,只要选择 Reactive Web 即可,如图所示。</p>
<p><img src="assets/e8756dce7ada604d9f29f2fd61d0f1721523318.png" alt="img" /></p>
<h3>配置 POM 依赖</h3>
<p>检查工程 POM 文件中,是否配置了 spring-boot-starter-webflux 依赖。如果是上面自动生成的,配置如下:</p>
<pre><code> &lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;io.projectreactor&lt;/groupId&gt;
&lt;artifactId&gt;reactor-test&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
</code></pre>
<p>spring-boot-starter-webflux 依赖,是我们核心需要学习 webflux 的包,里面默认包含了 spring-boot-starter-reactor-netty 、spring 5 webflux 包,也就是说默认是通过 netty 启动的。</p>
<p>reactor-test、spring-boot-starter-test 两个依赖搭配是用于单元测试。</p>
<p>spring-boot-maven-plugin 是 Spring Boot Maven 插件,可以运行、编译等调用。</p>
<h3>编写处理器类 Handler</h3>
<p>新建包 org.spring.springboot.handler作为编写功能处理类。新建城市City例子的处理类 CityHandler代码如下</p>
<pre><code>import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class CityHandler {
public Mono&lt;ServerResponse&gt; helloCity(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromObject(&quot;Hello, City!&quot;));
}
}
</code></pre>
<p>ServerResponse 是对响应的封装,可以设置响应状态、响应头、响应正文。比如 ok 代表的是 200 响应码、MediaType 枚举是代表这文本内容类型、返回的是 String 的对象。</p>
<p>这里用 Mono 作为返回对象,是因为返回包含了一个 ServerResponse 对象,而不是多个元素。</p>
<h3>编写路由器类 Router</h3>
<p>新建 org.spring.springboot.router 包作为编写路由器类。新建城市City例子的路由类 CityRouter代码如下</p>
<pre><code>import org.spring.springboot.handler.CityHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
@Configuration
public class CityRouter {
@Bean
public RouterFunction&lt;ServerResponse&gt; routeCity(CityHandler cityHandler) {
return RouterFunctions
.route(RequestPredicates.GET(&quot;/hello&quot;)
.and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
cityHandler::helloCity);
}
}
</code></pre>
<p>RouterFunctions 对请求路由处理类,即将请求路由到处理器,这里将一个 GET 请求 /hello 路由到处理器 cityHandler 的 helloCity 方法上。跟 Spring MVC 模式下的 HandleMapping 的作用类似。</p>
<p>RouterFunctions.route(RequestPredicate, HandlerFunction) 方法,对应的入参是请求参数和处理函数,如果请求匹配,就调用对应的处理器函数。</p>
<p>到这里一个简单的服务就写好了,下面怎么运行该服务。</p>
<h3>启动运行项目</h3>
<p>一个简单的 Spring Boot Webflux 工程就开发完毕了,下面运行工程验证下。使用 IDEA 右侧工具栏,点击 Maven Project Tab ,点击使用下 Maven 插件的 install 命令,或者使用命令行的形式,在工程根目录下,执行 Maven 清理和安装工程的指令:</p>
<pre><code>cd springboot-webflux-1-quickstart
mvn clean install
</code></pre>
<p>在控制台中看到成功的输出:</p>
<pre><code>... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2017-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------
</code></pre>
<h4>运行工程</h4>
<p>在 IDEA 中执行 Application 类启动,任意正常模式或者 Debug 模式,可以在控制台看到成功运行的输出:</p>
<pre><code>... 省略
2018-04-10 08:43:39.932 INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935 INFO 2052 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-04-10 08:43:39.960 INFO 2052 --- [ main] org.spring.springboot.Application : Started Application in 6.547 seconds (JVM running for 9.851)
</code></pre>
<p>一看,确实是 Netty 启动的。</p>
<p>打开浏览器,访问 /hello 地址,会看到如图所示的返回结果:</p>
<p><img src="assets/42a9f1eaa1ee54923556727eac2216481523320.png" alt="file" /></p>
<h3>总结</h3>
<p>本文主要讲了 Spring Boot 2.0 WebFlux 背景和快速入门使用,用的是基于功能性端点去创建一个服务,但这个有点代码偏多。下一课一个 CRUD 我们使用注解控制层,让开发更方便。</p>
</div>
</div>
<div>
<div style="float: left">
<a href="/专栏/案例上手 Spring Boot WebFlux/01 导读:课程概要.md.html">上一页</a>
</div>
<div style="float: right">
<a href="/专栏/案例上手 Spring Boot WebFlux/03 WebFlux Web CRUD 实践.md.html">下一页</a>
</div>
</div>
</div>
</div>
</div>
</div>
<a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>
<script defer src="https://static.cloudflareinsights.com/beacon.min.js/v652eace1692a40cfa3763df669d7439c1639079717194" integrity="sha512-Gi7xpJR8tSkrpF7aordPZQlW2DLtzUlZcumS8dMQjwDHEnw9I7ZLyiOj/6tZStRBGtGgN6ceN6cMH8z7etPGlw==" data-cf-beacon='{"rayId":"70997930a9ce3cfa","version":"2021.12.0","r":1,"token":"1f5d475227ce4f0089a7cff1ab17c0f5","si":100}' crossorigin="anonymous"></script>
</body>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-NPSEEVD756"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-NPSEEVD756');
var path = window.location.pathname
var cookie = getCookie("lastPath");
console.log(path)
if (path.replace("/", "") === "") {
if (cookie.replace("/", "") !== "") {
console.log(cookie)
document.getElementById("tip").innerHTML = "<a href='" + cookie + "'>跳转到上次进度</a>"
}
} else {
setCookie("lastPath", path)
}
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (180 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires + ";path = /";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return "";
}
</script>
</html>

View File

@@ -1,918 +1,459 @@
<!DOCTYPE html>
<!-- saved from url=(0046)https://kaiiiz.github.io/hexo-theme-book-demo/ -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
<link rel="icon" href="/static/favicon.png">
<title>05 WebFlux 整合 Thymeleaf.md.html</title>
<!-- Spectre.css framework -->
<link rel="stylesheet" href="/static/index.css">
<!-- theme css & js -->
<meta name="generator" content="Hexo 4.2.0">
</head>
<body>
<div class="book-container">
<div class="book-sidebar">
<div class="book-brand">
<a href="/">
<img src="/static/favicon.png">
<span>技术文章摘抄</span>
</a>
</div>
<div class="book-menu uncollapsible">
<ul class="uncollapsible">
<li><a href="/" class="current-tab">首页</a></li>
</ul>
<ul class="uncollapsible">
<li><a href="../">上一级</a></li>
</ul>
<ul class="uncollapsible">
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/01 导读:课程概要.md.html">01 导读:课程概要.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/02 WebFlux 快速入门实践.md.html">02 WebFlux 快速入门实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/03 WebFlux Web CRUD 实践.md.html">03 WebFlux Web CRUD 实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/04 WebFlux 整合 MongoDB.md.html">04 WebFlux 整合 MongoDB.md.html</a>
</li>
<li>
<a class="current-tab" href="/专栏/案例上手 Spring Boot WebFlux/05 WebFlux 整合 Thymeleaf.md.html">05 WebFlux 整合 Thymeleaf.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html">06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/07 WebFlux 整合 Redis.md.html">07 WebFlux 整合 Redis.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/08 WebFlux 中 Redis 实现缓存.md.html">08 WebFlux 中 Redis 实现缓存.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/09 WebFlux 中 WebSocket 实现通信.md.html">09 WebFlux 中 WebSocket 实现通信.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/10 WebFlux 集成测试及部署.md.html">10 WebFlux 集成测试及部署.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/11 WebFlux 实战图书管理系统.md.html">11 WebFlux 实战图书管理系统.md.html</a>
</li>
</ul>
</div>
</div>
<div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
<div class="sidebar-toggle-inner"></div>
</div>
<script>
function add_inner() {
let inner = document.querySelector('.sidebar-toggle-inner')
inner.classList.add('show')
}
function remove_inner() {
let inner = document.querySelector('.sidebar-toggle-inner')
inner.classList.remove('show')
}
function sidebar_toggle() {
let sidebar_toggle = document.querySelector('.sidebar-toggle')
let sidebar = document.querySelector('.book-sidebar')
let content = document.querySelector('.off-canvas-content')
if (sidebar_toggle.classList.contains('extend')) { // show
sidebar_toggle.classList.remove('extend')
sidebar.classList.remove('hide')
content.classList.remove('extend')
} else { // hide
sidebar_toggle.classList.add('extend')
sidebar.classList.add('hide')
content.classList.add('extend')
}
}
function open_sidebar() {
let sidebar = document.querySelector('.book-sidebar')
let overlay = document.querySelector('.off-canvas-overlay')
sidebar.classList.add('show')
overlay.classList.add('show')
}
function hide_canvas() {
let sidebar = document.querySelector('.book-sidebar')
let overlay = document.querySelector('.off-canvas-overlay')
sidebar.classList.remove('show')
overlay.classList.remove('show')
}
</script>
<div class="off-canvas-content">
<div class="columns">
<div class="column col-12 col-lg-12">
<div class="book-navbar">
<!-- For Responsive Layout -->
<header class="navbar">
<section class="navbar-section">
<a onclick="open_sidebar()">
<i class="icon icon-menu"></i>
</a>
</section>
</header>
</div>
<div class="book-content" style="max-width: 960px; margin: 0 auto;
overflow-x: auto;
overflow-y: hidden;">
<div class="book-post">
<p id="tip" align="center"></p>
<div><h1>05 WebFlux 整合 Thymeleaf</h1>
<p>上一篇介绍的是用 MongoDB 来实现 WebFlux 对数据源的操作,那么有了数据需要渲染到前台给用户展示,这就是本文关心的 View 层View 的表现形式有很多,比如 JSON 和 HTML。开发中常用模板语言很常见的有 Thymeleaf、Freemarker等那什么是模板语言</p>
<p>常见的模板语言都包含以下几个概念数据Data、模板Template、模板引擎Template Engine和结果文档Result Documents</p>
<ul>
<li>数据</li>
</ul>
<p>数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。</p>
<ul>
<li>模板</li>
</ul>
<p>模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。</p>
<ul>
<li>模板引擎</li>
</ul>
<p>模板引擎(这里特指用于 Web 开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的 HTML 文档。</p>
<ul>
<li>结果文档</li>
</ul>
<p>一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的 HTML 文档。</p>
<p>模板语言用途广泛,常见的用途如下:</p>
<ul>
<li>页面渲染</li>
<li>文档生成</li>
<li>代码生成</li>
<li>所有 “数据+模板=文本” 的应用场景</li>
</ul>
<p>Spring Boot 推荐使用的模板语言是 Thymeleaf那什么是 Thymeleaf</p>
<p>官方的解释如下:</p>
<pre><code>Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
</code></pre>
<p>Thymeleaf 是现代的模板语言引擎,可以独立运行也可以服务于 Web主要目标是为开发提供天然的模板并且能在 HTML 里面准确的显示。</p>
<p>Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 后推荐使用。目前是 Spring 5 自然更加推荐。</p>
<h3>结构</h3>
<p>类似上面讲的工程搭建,新建一个工程编写此案例,工程图如图所示:</p>
<p><img src="assets/3b8c0edab9491e422bef6003299895911524185.png" alt="img" /></p>
<p>目录如下:</p>
<ul>
<li>org.spring.springboot.webflux.controllerController 层</li>
<li>org.spring.springboot.dao数据操作层 DAO</li>
<li>org.spring.springboot.domain实体类</li>
<li>org.spring.springboot.handler业务逻辑层</li>
<li>Application应用启动类</li>
<li>application.properties应用配置文件</li>
<li>pom.xml maven 配置</li>
<li>application.properties 配置文件</li>
</ul>
<p>模板是会用到下面两个目录:</p>
<ul>
<li>static 目录是存放 CSS、JS 等资源文件;</li>
<li>templates 目录是存放视图。</li>
</ul>
<p>本文重点在 Controller 层 和 templates 视图的编写。</p>
<h3>新增 POM 依赖与配置</h3>
<p>在 pom.xml 配置新的依赖:</p>
<pre><code> &lt;dependencies&gt;
&lt;!-- Spring Boot Web Flux 依赖 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;!-- 模板引擎 Thymeleaf 依赖 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;!-- Spring Boot Test 依赖 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- Junit --&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.12&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<p>这里我们增加了 Thymeleaf 依赖,但不用在 application.properties - 应用配置文件中配置任何配置。默认启动其默认配置,如需修改配置参考 Thymeleaf 依赖配置,如下:</p>
<pre><code>spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
</code></pre>
<p>包括常用的编码、是否开启缓存等等。</p>
<h3>WebFlux 中使用 Thymeleaf</h3>
<p>在 CityWebFluxController 控制层,添加两个方法如下:</p>
<pre><code> @GetMapping(&quot;/hello&quot;)
public Mono&lt;String&gt; hello(final Model model) {
model.addAttribute(&quot;name&quot;, &quot;泥瓦匠&quot;);
model.addAttribute(&quot;city&quot;, &quot;浙江温岭&quot;);
String path = &quot;hello&quot;;
return Mono.create(monoSink -&gt; monoSink.success(path));
}
private static final String CITY_LIST_PATH_NAME = &quot;cityList&quot;;
@GetMapping(&quot;/page/list&quot;)
public String listPage(final Model model) {
final Flux&lt;City&gt; cityFluxList = cityHandler.findAllCity();
model.addAttribute(&quot;cityList&quot;, cityFluxList);
return CITY_LIST_PATH_NAME;
}
</code></pre>
<p>解释下语法:</p>
<ul>
<li>返回值 Mono 或者 String 都行,但是 Mono 代表着我这个返回 View 也是回调的。</li>
<li>return 字符串,该字符串对应的目录在 resources/templates 下的模板名字。</li>
<li>Model 对象来进行数据绑定到视图。</li>
<li>一般会集中用常量管理模板视图的路径。</li>
</ul>
<h3>Tymeleaf 视图</h3>
<p>然后编写两个视图 hello 和 cityList代码分别如下。</p>
<p>hello.html</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;zh-CN&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;/&gt;
&lt;title&gt;欢迎页面&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1 &gt;你好,欢迎来自&lt;p th:text=&quot;${city}&quot;&gt;&lt;/p&gt;&lt;p th:text=&quot;${name}&quot;&gt;&lt;/p&gt;&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>cityList.html</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;zh-CN&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;/&gt;
&lt;title&gt;城市列表&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
&lt;table&gt;
&lt;legend&gt;
&lt;strong&gt;城市列表&lt;/strong&gt;
&lt;/legend&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;城市编号&lt;/th&gt;
&lt;th&gt;省份编号&lt;/th&gt;
&lt;th&gt;名称&lt;/th&gt;
&lt;th&gt;描述&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr th:each=&quot;city : ${cityList}&quot;&gt;
&lt;td th:text=&quot;${city.id}&quot;&gt;&lt;/td&gt;
&lt;td th:text=&quot;${city.provinceId}&quot;&gt;&lt;/td&gt;
&lt;td th:text=&quot;${city.cityName}&quot;&gt;&lt;/td&gt;
&lt;td th:text=&quot;${city.description}&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>常用语法糖如下:</p>
<ul>
<li>${...}:变量表达式;</li>
<li>th:text处理 Tymeleaf 表达式;</li>
<li>th:each遍历表达式可遍历的对象有实现 java.util.Iterable、java.util.Map遍历时取 java.util.Map.Entry、array 等。</li>
</ul>
<p>还有很多使用,可以参考<a href="http://www.thymeleaf.org/documentation.html">官方文档</a></p>
<h3>运行工程</h3>
<p>下面运行工程验证下,使用 IDEA 右侧工具栏,点击 Maven Project Tab ,点击使用下 Maven 插件的 install 命令;或者使用命令行的形式,在工程根目录下,执行 Maven 清理和安装工程的指令:</p>
<pre><code>cd springboot-webflux-4-thymeleaf
mvn clean install
</code></pre>
<p>在控制台中看到成功的输出:</p>
<pre><code>... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2017-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>在 IDEA 中执行 Application 类启动,任意正常模式或者 Debug 模式,可以在控制台看到成功运行的输出:</p>
<pre><code>... 省略
2018-04-10 08:43:39.932 INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935 INFO 2052 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-04-10 08:43:39.960 INFO 2052 --- [ main] org.spring.springboot.Application : Started Application in 6.547 seconds (JVM running for 9.851)
</code></pre>
<p>打开浏览器,访问 http://localhost:8080/city/hello ,可以看到如图的响应:</p>
<p><img src="assets/9e0580fa073aa29426bda0aab4f41da51524186.png" alt="img" /></p>
<p>继续访问 http://localhost:8080/city/page/list , 发现没有值,那么按照上一讲插入几条数据即可有值,如图:</p>
<p><img src="assets/66e6502b86c02a83bf56daa93eb9bc1a1524186.png" alt="img" /></p>
<h3>总结</h3>
<p>这里探讨了 Spring WebFlux 的如何整合 Thymeleaf整合其他模板语言 Thymeleaf、Freemarker就大同小异了。下面我们可以整合 Thymeleaf 和 MongoBD 来实现一个整体的简单案例。</p>
</div>
</div>
<div>
<div style="float: left">
<a href="/专栏/案例上手 Spring Boot WebFlux/04 WebFlux 整合 MongoDB.md.html">上一页</a>
</div>
<div style="float: right">
<a href="/专栏/案例上手 Spring Boot WebFlux/06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html">下一页</a>
</div>
</div>
</div>
</div>
</div>
</div>
<a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>
<script defer src="https://static.cloudflareinsights.com/beacon.min.js/v652eace1692a40cfa3763df669d7439c1639079717194" integrity="sha512-Gi7xpJR8tSkrpF7aordPZQlW2DLtzUlZcumS8dMQjwDHEnw9I7ZLyiOj/6tZStRBGtGgN6ceN6cMH8z7etPGlw==" data-cf-beacon='{"rayId":"709979363ed33cfa","version":"2021.12.0","r":1,"token":"1f5d475227ce4f0089a7cff1ab17c0f5","si":100}' crossorigin="anonymous"></script>
</body>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-NPSEEVD756"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-NPSEEVD756');
var path = window.location.pathname
var cookie = getCookie("lastPath");
console.log(path)
if (path.replace("/", "") === "") {
if (cookie.replace("/", "") !== "") {
console.log(cookie)
document.getElementById("tip").innerHTML = "<a href='" + cookie + "'>跳转到上次进度</a>"
}
} else {
setCookie("lastPath", path)
}
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (180 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires + ";path = /";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return "";
}
</script>
</html>

View File

@@ -1,944 +1,472 @@
<!DOCTYPE html>
<!-- saved from url=(0046)https://kaiiiz.github.io/hexo-theme-book-demo/ -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
<link rel="icon" href="/static/favicon.png">
<title>08 WebFlux 中 Redis 实现缓存.md.html</title>
<!-- Spectre.css framework -->
<link rel="stylesheet" href="/static/index.css">
<!-- theme css & js -->
<meta name="generator" content="Hexo 4.2.0">
</head>
<body>
<div class="book-container">
<div class="book-sidebar">
<div class="book-brand">
<a href="/">
<img src="/static/favicon.png">
<span>技术文章摘抄</span>
</a>
</div>
<div class="book-menu uncollapsible">
<ul class="uncollapsible">
<li><a href="/" class="current-tab">首页</a></li>
</ul>
<ul class="uncollapsible">
<li><a href="../">上一级</a></li>
</ul>
<ul class="uncollapsible">
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/01 导读:课程概要.md.html">01 导读:课程概要.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/02 WebFlux 快速入门实践.md.html">02 WebFlux 快速入门实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/03 WebFlux Web CRUD 实践.md.html">03 WebFlux Web CRUD 实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/04 WebFlux 整合 MongoDB.md.html">04 WebFlux 整合 MongoDB.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/05 WebFlux 整合 Thymeleaf.md.html">05 WebFlux 整合 Thymeleaf.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html">06 WebFlux 中 Thymeleaf 和 MongoDB 实践.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/07 WebFlux 整合 Redis.md.html">07 WebFlux 整合 Redis.md.html</a>
</li>
<li>
<a class="current-tab" href="/专栏/案例上手 Spring Boot WebFlux/08 WebFlux 中 Redis 实现缓存.md.html">08 WebFlux 中 Redis 实现缓存.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/09 WebFlux 中 WebSocket 实现通信.md.html">09 WebFlux 中 WebSocket 实现通信.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/10 WebFlux 集成测试及部署.md.html">10 WebFlux 集成测试及部署.md.html</a>
</li>
<li>
<a href="/专栏/案例上手 Spring Boot WebFlux/11 WebFlux 实战图书管理系统.md.html">11 WebFlux 实战图书管理系统.md.html</a>
</li>
</ul>
</div>
</div>
<div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
<div class="sidebar-toggle-inner"></div>
</div>
<script>
function add_inner() {
let inner = document.querySelector('.sidebar-toggle-inner')
inner.classList.add('show')
}
function remove_inner() {
let inner = document.querySelector('.sidebar-toggle-inner')
inner.classList.remove('show')
}
function sidebar_toggle() {
let sidebar_toggle = document.querySelector('.sidebar-toggle')
let sidebar = document.querySelector('.book-sidebar')
let content = document.querySelector('.off-canvas-content')
if (sidebar_toggle.classList.contains('extend')) { // show
sidebar_toggle.classList.remove('extend')
sidebar.classList.remove('hide')
content.classList.remove('extend')
} else { // hide
sidebar_toggle.classList.add('extend')
sidebar.classList.add('hide')
content.classList.add('extend')
}
}
function open_sidebar() {
let sidebar = document.querySelector('.book-sidebar')
let overlay = document.querySelector('.off-canvas-overlay')
sidebar.classList.add('show')
overlay.classList.add('show')
}
function hide_canvas() {
let sidebar = document.querySelector('.book-sidebar')
let overlay = document.querySelector('.off-canvas-overlay')
sidebar.classList.remove('show')
overlay.classList.remove('show')
}
</script>
<div class="off-canvas-content">
<div class="columns">
<div class="column col-12 col-lg-12">
<div class="book-navbar">
<!-- For Responsive Layout -->
<header class="navbar">
<section class="navbar-section">
<a onclick="open_sidebar()">
<i class="icon icon-menu"></i>
</a>
</section>
</header>
</div>
<div class="book-content" style="max-width: 960px; margin: 0 auto;
overflow-x: auto;
overflow-y: hidden;">
<div class="book-post">
<p id="tip" align="center"></p>
<div><h1>08 WebFlux 中 Redis 实现缓存</h1>
<h3>前言</h3>
<p>首先补充下上一篇的内容RedisTemplate 实现操作 Redis但操作是同步的不是 Reactive 的。自然,支持 Reactive 的操作类为 ReactiveRedisTemplate下面我们写个小案例。</p>
<h3>ReactiveRedisTemplate</h3>
<p>在上一篇工程中,新建 CityWebFluxReactiveController 类,路由为 /city2 开头。</p>
<pre><code>@RestController
@RequestMapping(value = &quot;/city2&quot;)
public class CityWebFluxReactiveController {
@Autowired
private ReactiveRedisTemplate reactiveRedisTemplate;
@GetMapping(value = &quot;/{id}&quot;)
public Mono&lt;City&gt; findCityById(@PathVariable(&quot;id&quot;) Long id) {
String key = &quot;city_&quot; + id;
ReactiveValueOperations&lt;String, City&gt; operations = reactiveRedisTemplate.opsForValue();
Mono&lt;City&gt; city = operations.get(key);
return city;
}
@PostMapping
public Mono&lt;City&gt; saveCity(@RequestBody City city) {
String key = &quot;city_&quot; + city.getId();
ReactiveValueOperations&lt;String, City&gt; operations = reactiveRedisTemplate.opsForValue();
return operations.getAndSet(key, city);
}
@DeleteMapping(value = &quot;/{id}&quot;)
public Mono&lt;Long&gt; deleteCity(@PathVariable(&quot;id&quot;) Long id) {
String key = &quot;city_&quot; + id;
return reactiveRedisTemplate.delete(key);
}
}
</code></pre>
<ul>
<li>写法和以前保持一致,@Autowired 注入 ReactiveRedisTemplate 对象。</li>
<li>ReactiveValueOperations 是 String或 value的操作视图操作视图还有 ReactiveHashOperations、ReactiveListOperations、ReactiveSetOperations 和 ReactiveZSetOperations 等。</li>
<li>不一样的是,操作视图 set 方法是操作 City 对象,但可以 get 回 Mono 或者 Flux 对象。</li>
</ul>
<h3>结构</h3>
<p>回到这个工程,新建一个工程编写整合 Redis 实现缓存案例,工程如图:</p>
<p><img src="assets/3b4f95fda4771ca70c5bbc644f82a0c01525318.png" alt="file" /></p>
<p>目录核心如下:</p>
<ul>
<li>pom.xml maven 配置</li>
<li>application.properties 配置文件</li>
<li>domain 实体类</li>
<li>dao mongodb数据操作层</li>
<li>handler 业务层,本文要点</li>
<li>controller 控制层</li>
</ul>
<p><a href="https://github.com/JeffLi1993/springboot-learning-example">单击这里查看源代码</a></p>
<h3>控制层 CityWebFluxController</h3>
<p>代码如下:</p>
<pre><code>@RestController
@RequestMapping(value = &quot;/city&quot;)
public class CityWebFluxController {
@Autowired
private CityHandler cityHandler;
@GetMapping(value = &quot;/{id}&quot;)
public Mono&lt;City&gt; findCityById(@PathVariable(&quot;id&quot;) Long id) {
return cityHandler.findCityById(id);
}
@GetMapping()
public Flux&lt;City&gt; findAllCity() {
return cityHandler.findAllCity();
}
@PostMapping()
public Mono&lt;City&gt; saveCity(@RequestBody City city) {
return cityHandler.save(city);
}
@PutMapping()
public Mono&lt;City&gt; modifyCity(@RequestBody City city) {
return cityHandler.modifyCity(city);
}
@DeleteMapping(value = &quot;/{id}&quot;)
public Mono&lt;Long&gt; deleteCity(@PathVariable(&quot;id&quot;) Long id) {
return cityHandler.deleteCity(id);
}
}
</code></pre>
<h3>CityHandler 业务层</h3>
<p>目前,@Cacheable 等注解形式实现缓存没有很好的集成,二者 Mono / Flux 对象没有实现 Serializable无法通过默认序列化器解决方式是需要自定义序列化这里通过手动方式与 Redis 手动集成,并实现缓存策略。</p>
<p><a href="http://coolshell.cn/articles/17416.html">参考《缓存更新的套路》</a>缓存更新的模式有四种Cache aside、Read through、Write through、Write behind caching。</p>
<p>这里使用的是 Cache Aside 策略,从三个维度(摘自耗子叔叔博客):</p>
<ul>
<li>失效:应用程序先从 Cache 取数据,没有得到,则从数据库中取数据,成功后,放到缓存中。</li>
<li>命中:应用程序从 Cache 中取数据,取到后返回。</li>
<li>更新:先把数据存到数据库中,成功后,再让缓存失效。</li>
</ul>
<p>代码如下:</p>
<pre><code>@Component
public class CityHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CityHandler.class);
@Autowired
private RedisTemplate redisTemplate;
private final CityRepository cityRepository;
@Autowired
public CityHandler(CityRepository cityRepository) {
this.cityRepository = cityRepository;
}
public Mono&lt;City&gt; save(City city) {
return cityRepository.save(city);
}
public Mono&lt;City&gt; findCityById(Long id) {
// 从缓存中获取城市信息
String key = &quot;city_&quot; + id;
ValueOperations&lt;String, City&gt; operations = redisTemplate.opsForValue();
// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
City city = operations.get(key);
LOGGER.info(&quot;CityHandler.findCityById() : 从缓存中获取了城市 &gt;&gt; &quot; + city.toString());
return Mono.create(cityMonoSink -&gt; cityMonoSink.success(city));
}
// 从 MongoDB 中获取城市信息
Mono&lt;City&gt; cityMono = cityRepository.findById(id);
if (cityMono == null)
return cityMono;
// 插入缓存
cityMono.subscribe(cityObj -&gt; {
operations.set(key, cityObj);
LOGGER.info(&quot;CityHandler.findCityById() : 城市插入缓存 &gt;&gt; &quot; + cityObj.toString());
});
return cityMono;
}
public Flux&lt;City&gt; findAllCity() {
return cityRepository.findAll().cache();
}
public Mono&lt;City&gt; modifyCity(City city) {
Mono&lt;City&gt; cityMono = cityRepository.save(city);
// 缓存存在,删除缓存
String key = &quot;city_&quot; + city.getId();
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
LOGGER.info(&quot;CityHandler.modifyCity() : 从缓存中删除城市 ID &gt;&gt; &quot; + city.getId());
}
return cityMono;
}
public Mono&lt;Long&gt; deleteCity(Long id) {
cityRepository.deleteById(id);
// 缓存存在,删除缓存
String key = &quot;city_&quot; + id;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
LOGGER.info(&quot;CityHandler.deleteCity() : 从缓存中删除城市 ID &gt;&gt; &quot; + id);
}
return Mono.create(cityMonoSink -&gt; cityMonoSink.success(id));
}
}
</code></pre>
<p>首先这里注入了 RedisTemplate 对象,联想到 Spring 的 JdbcTemplate RedisTemplate 封装了 RedisConnection具有连接管理序列化和 Redis 操作等功能,还有针对 String 的支持对象 StringRedisTemplate。</p>
<p>回到更新缓存的逻辑。</p>
<p>a. findCityById 获取城市逻辑:</p>
<ul>
<li>如果缓存存在,从缓存中获取城市信息;</li>
<li>如果缓存不存在,从 DB 中获取城市信息,然后插入缓存。</li>
</ul>
<p>b. deleteCity 删除 / modifyCity 更新城市逻辑:</p>
<ul>
<li>如果缓存存在,删除;</li>
<li>如果缓存不存在,不操作。</li>
</ul>
<h3>运行工程</h3>
<p>一个操作 Redis 工程就开发完毕了,下面运行工程验证下。使用 IDEA 右侧工具栏,点击 Maven Project Tab点击使用下 Maven 插件的 install 命令;或者使用命令行的形式,在工程根目录下,执行 Maven 清理和安装工程的指令:</p>
<pre><code>cd springboot-webflux-7-redis-cache
mvn clean install
</code></pre>
<p>在控制台中看到成功的输出:</p>
<pre><code>... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2018-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>在 IDEA 中执行 Application 类启动,任意正常模式或者 Debug 模式,可以在控制台看到成功运行的输出:</p>
<pre><code>... 省略
2018-04-10 08:43:39.932 INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935 INFO 2052 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-04-10 08:43:39.960 INFO 2052 --- [ main] org.spring.springboot.Application : Started Application in 6.547 seconds (JVM running for 9.851)
</code></pre>
<p>打开 POST MAN 工具,开发必备。进行下面操作:</p>
<p><strong>新增城市信息 POST http://127.0.0.1:8080/city</strong></p>
<p><img src="assets/f69fa5b09730de686ef4837824da48e71523883-1608971278890.png" alt="file" /></p>
<p><strong>获取城市信息 GET http://127.0.0.1:8080/city/2</strong></p>
<p><img src="assets/2e129648b8e574a54ff7940f00f1dc591524819-1608971278898.png" alt="file" /></p>
<p>再请求一次,获取城市信息会发现数据获取的耗时快了很多,服务端 Console 输出的日志:</p>
<pre><code>2017-04-13 18:29:00.273 INFO 13038 --- [nio-8080-exec-1] findCityById() : 城市插入缓存 &gt;&gt; City{id=12, provinceId=3, cityName='三亚', description='水好,天蓝'}
2017-04-13 18:29:03.145 INFO 13038 --- [nio-8080-exec-2] findCityById() : 从缓存中获取了城市 &gt;&gt; City{id=12, provinceId=3, cityName='三亚', description='水好,天蓝'}
</code></pre>
<p>可见,第一次是从数据库 MongoDB 获取数据,并插入缓存,第二次直接从缓存中取。</p>
<p>更新 / 删除城市信息,这两种操作中,如果缓存有对应的数据,则删除缓存。服务端 Console 输出的日志:</p>
<pre><code>2017-04-13 18:29:52.248 INFO 13038 --- [nio-8080-exec-9] deleteCity() : 从缓存中删除城市 ID &gt;&gt; 12
</code></pre>
<h3>总结</h3>
<p>这一讲,主要补充了 Redis 对响应式的支持操作,以及缓存更新策略及实际应用小例子。</p>
</div>
</div>
<div>
<div style="float: left">
<a href="/专栏/案例上手 Spring Boot WebFlux/07 WebFlux 整合 Redis.md.html">上一页</a>
</div>
<div style="float: right">
<a href="/专栏/案例上手 Spring Boot WebFlux/09 WebFlux 中 WebSocket 实现通信.md.html">下一页</a>
</div>
</div>
</div>
</div>
</div>
</div>
<a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>
<script defer src="https://static.cloudflareinsights.com/beacon.min.js/v652eace1692a40cfa3763df669d7439c1639079717194" integrity="sha512-Gi7xpJR8tSkrpF7aordPZQlW2DLtzUlZcumS8dMQjwDHEnw9I7ZLyiOj/6tZStRBGtGgN6ceN6cMH8z7etPGlw==" data-cf-beacon='{"rayId":"7099793bdb0e3cfa","version":"2021.12.0","r":1,"token":"1f5d475227ce4f0089a7cff1ab17c0f5","si":100}' crossorigin="anonymous"></script>
</body>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-NPSEEVD756"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-NPSEEVD756');
var path = window.location.pathname
var cookie = getCookie("lastPath");
console.log(path)
if (path.replace("/", "") === "") {
if (cookie.replace("/", "") !== "") {
console.log(cookie)
document.getElementById("tip").innerHTML = "<a href='" + cookie + "'>跳转到上次进度</a>"
}
} else {
setCookie("lastPath", path)
}
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (180 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires + ";path = /";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return "";
}
</script>
</html>