第05课:WebFlux 中 Thymeleaf 和 MongoDB 实践

前言

本节内容主要还是总结上面两篇内容的操作,并实现一个复杂查询的小案例,那么没安装 MongoDB 的可以进行下面的安装流程。

Docker 安装 MognoDB 并启动如下。

(1)创建挂载目录:

docker volume create mongo_data_db
docker volume create mongo_data_configdb

(2)启动 MognoDB:

docker run -d \
--name mongo \
-v mongo_data_configdb:/data/configdb \
-v mongo_data_db:/data/db \
-p 27017:27017 \
mongo \
--auth

(3)初始化管理员账号:

docker exec -it mongo     mongo              admin
// 容器名 // mongo命令 数据库名 # 创建最高权限用户
db.createUser({ user: 'admin', pwd: 'admin', roles: [ { role: "root", db: "admin" } ] });

(4)测试连通性:

docker run -it --rm --link mongo:mongo mongo mongo -u admin -p admin --authenticationDatabase admin mongo/admin

MognoDB 基本操作

类似 MySQL 命令,显示库列表:

show dbs

使用某数据库:

use admin

显示表列表:

show collections

如果存在 city 表,格式化显示 city 表内容:

db.city.find().pretty()

如果已经安装后,只要重启即可。

查看已有的镜像:

 docker images

然后 docker start mogno 即可,Mongo 是镜像唯一名词。

结构

类似上面讲的工程搭建,新建一个工程编写此案例,工程如图:

核心目录如下:

  • pom.xml Maven 依赖配置
  • application.properties 配置文件,配置 mongo 连接属性配置
  • dao 数据访问层
  • controller 展示层实现

新增 POM 依赖与配置

在 pom.xml 配置新的依赖:

    <!-- Spring Boot 响应式 MongoDB 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency> <!-- 模板引擎 Thymeleaf 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

类似配了 MySQL 和 JDBC 驱动,肯定得去配置数据库。在 application.properties 配置中启动 MongoDB 配置。

数据库名为 admin,账号密码也为 admin。

spring.data.mongodb.host=localhost
spring.data.mongodb.database=admin
spring.data.mongodb.port=27017
spring.data.mongodb.username=admin
spring.data.mongodb.password=admin

MongoDB 数据访问层 CityRepository

修改 CityRepository 类,代码如下:

import org.spring.springboot.domain.City;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository; @Repository
public interface CityRepository extends ReactiveMongoRepository<City, Long> { Mono<City> findByCityName(String cityName); }

CityRepository 接口只要继承 ReactiveMongoRepository 类即可。

这里实现了通过城市名找出唯一的城市对象方法:

Mono<City> findByCityName(String cityName);

复杂查询语句实现也很简单,只要依照接口实现规范,即可实现对应 MySQL 的 where 查询语句。这里 findByxxx 的 xxx 可以映射任何字段,包括主键等。

接口的命名是遵循规范的,常用命名规则如下:

关键字 方法命名
And findByNameAndPwd
Or findByNameOrSex
Is findById
Between findByIdBetween
Like findByNameLike
NotLike findByNameNotLike
OrderBy findByIdOrderByXDesc
Not findByNameNot

处理器类 Handler 和控制器类 Controller

修改下 Handler,代码如下:

@Component
public class CityHandler { private final CityRepository cityRepository; @Autowired
public CityHandler(CityRepository cityRepository) {
this.cityRepository = cityRepository;
} public Mono<City> save(City city) {
return cityRepository.save(city);
} public Mono<City> findCityById(Long id) { return cityRepository.findById(id);
} public Flux<City> findAllCity() { return cityRepository.findAll();
} public Mono<City> modifyCity(City city) { return cityRepository.save(city);
} public Mono<Long> deleteCity(Long id) {
cityRepository.deleteById(id);
return Mono.create(cityMonoSink -> cityMonoSink.success(id));
} public Mono<City> getByCityName(String cityName) {
return cityRepository.findByCityName(cityName);
}
}

新增对应的方法,直接返回 Mono 对象,不需要对 Mono 进行转换,因为 Mono 本身是个对象,可以被 View 层渲染。继续修改控制器类 Controller,代码如下:

    @Autowired
private CityHandler cityHandler; @GetMapping(value = "/{id}")
@ResponseBody
public Mono<City> findCityById(@PathVariable("id") Long id) {
return cityHandler.findCityById(id);
} @GetMapping()
@ResponseBody
public Flux<City> findAllCity() {
return cityHandler.findAllCity();
} @PostMapping()
@ResponseBody
public Mono<City> saveCity(@RequestBody City city) {
return cityHandler.save(city);
} @PutMapping()
@ResponseBody
public Mono<City> modifyCity(@RequestBody City city) {
return cityHandler.modifyCity(city);
} @DeleteMapping(value = "/{id}")
@ResponseBody
public Mono<Long> deleteCity(@PathVariable("id") Long id) {
return cityHandler.deleteCity(id);
} private static final String CITY_LIST_PATH_NAME = "cityList";
private static final String CITY_PATH_NAME = "city"; @GetMapping("/page/list")
public String listPage(final Model model) {
final Flux<City> cityFluxList = cityHandler.findAllCity();
model.addAttribute("cityList", cityFluxList);
return CITY_LIST_PATH_NAME;
} @GetMapping("/getByName")
public String getByCityName(final Model model,
@RequestParam("cityName") String cityName) {
final Mono<City> city = cityHandler.getByCityName(cityName);
model.addAttribute("city", city);
return CITY_PATH_NAME;
}

新增 getByName 路径,指向了新的页面 city。使用 @RequestParam 接收 GET 请求入参,接收的参数为 cityName,城市名称。视图返回值 Mono<String> 或者 String 都行。

Tymeleaf 视图

然后编写两个视图 city 和 cityList,代码分别如下。

city.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<title>城市</title>
</head> <body> <div> <table>
<legend>
<strong>城市单个查询</strong>
</legend>
<tbody>
<td th:text="${city.id}"></td>
<td th:text="${city.provinceId}"></td>
<td th:text="${city.cityName}"></td>
<td th:text="${city.description}"></td>
</tbody>
</table> </div> </body>
</html>

cityList.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<title>城市列表</title>
</head> <body> <div> <table>
<legend>
<strong>城市列表</strong>
</legend>
<thead>
<tr>
<th>城市编号</th>
<th>省份编号</th>
<th>名称</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr th:each="city : ${cityList}">
<td th:text="${city.id}"></td>
<td th:text="${city.provinceId}"></td>
<td th:text="${city.cityName}"></td>
<td th:text="${city.description}"></td>
</tr>
</tbody>
</table> </div> </body>
</html>

运行工程

一个 CRUD 的 Spring Boot Webflux 工程就开发完毕了,下面运行工程验证一下。使用 IDEA 右侧工具栏,单击 Maven Project Tab 按钮,然后单击使用下 Maven 插件的 install 命令;或者使用命令行的形式,在工程根目录下,执行 Maven 清理和安装工程的指令:

cd springboot-webflux-5-thymeleaf-mongodb
mvn clean install

在控制台中看到成功的输出:

... 省略
[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] ------------------------------------------------------------------------

在 IDEA 中执行 Application 类启动,任意正常模式或者 Debug 模式。可以在控制台看到成功运行的输出:

... 省略
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)

打开 POST MAN 工具,开发必备,进行下面操作。

新增城市信息 POST http://127.0.0.1:8080/city:

打开浏览器,访问 http://localhost:8080/city/getByName?cityName=杭州,可以看到如图的响应:

继续访问 http://localhost:8080/city/page/list,发现没有值,那么按照上一篇的内容插入几条数据即可有值,如图:

总结

这里初步实现了一个简单的整合,具体复杂的案例我们在后面的综合案例中实现,会很酷炫。下面整合 Redis,基于 Redis 可以实现常用的缓存、锁,下一篇我们将学习如何整合 Reids。

源代码地址详见这里 :https://github.com/JeffLi1993/springboot-learning-example

Spring Boot WebFlu-05——WebFlux 中 Thymeleaf 和 MongoDB 实践的更多相关文章

  1. WebFlux 集成 Thymeleaf 、 Mongodb 实践 - Spring Boot(六)

    这是泥瓦匠的第105篇原创 文章工程: JDK 1.8 Maven 3.5.2 Spring Boot 2.1.3.RELEASE 工程名:springboot-webflux-5-thymeleaf ...

  2. 黑马_13 Spring Boot:05.spring boot 整合其他技术

    13 Spring Boot: 01.spring boot 介绍&&02.spring boot 入门 04.spring boot 配置文件 05.spring boot 整合其他 ...

  3. Spring Boot 监听 Activemq 中的特定 topic ,并将数据通过 RabbitMq 发布出去

    1.Spring Boot 和 ActiveMQ .RabbitMQ 简介 最近因为公司的项目需要用到 Spring Boot , 所以自学了一下, 发现它与 Spring 相比,最大的优点就是减少了 ...

  4. spring boot 项目从配置文件中读取maven 的pom.xml 文件标签的内容。

    需求: 将pom.xml 文件中的版本号读取到配置文件并打印到日志中. 第一步: 在pom.xml 中添加以下标签. 第二步: 将version 标签的值读取到配置文件中 这里使用 @@  而不是  ...

  5. Spring Boot 2.0 WebFlux 教程 (一) | 入门篇

    目录 一.什么是 Spring WebFlux 二.WebFlux 的优势&提升性能? 三.WebFlux 应用场景 四.选 WebFlux 还是 Spring MVC? 五.异同点 六.简单 ...

  6. spring boot ----> 常用模板freemarker和thymeleaf

    ===========================freemarker=================================== freemarker 官网:https://freem ...

  7. 实战基于Spring Boot 2的WebFlux和mLab搭建反应式Web

    Spring Framework 5带来了新的Reactive Stack非阻塞式Web框架:Spring WebFlux.作为与Spring MVC并行使用的Web框架,Spring WebFlux ...

  8. spring boot 使用thymeleaf3.0以及thymeleaf的热部署

    spring boot 截止1.5.4,默认使用thymeleaf2.0,会有一些很蛋疼的地方比如xml格式之类的,具体哪些就不说了 -> 替换为3.0版本 pom中加入 <propert ...

  9. Spring Boot (4) 静态页面和Thymeleaf模板

    静态页面 spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下 /static /public /resources /ME ...

随机推荐

  1. java之try catch finally

    try{ }catch(Exception e){ }finally{ } java异常处理在编程中很常见,将可能抛出异常的语句放在try{}中,若有异常抛出,则try{}中抛出异常语句之后的语句不再 ...

  2. HashSet添加操作底层判读(Object类型)

    Object类型添加操作判读 第一步:程序首先创建一个Object泛型的Set数组,这里用到了上转型: 第二步:执行object里面的add添加方法,传进的值为"JAVA": 首先 ...

  3. Jenkins + Docker + ASP.NET Core自动化部署

    本来没想着要写这篇博客,但是在实操过程中,一个是被网络问题搞炸了心态(真心感觉网络能把人搞疯,别人下个包.下个镜像几秒钟搞定,我看着我的几KB小水管真是有苦说不出),另一个就是这里面坑还是有一些的,写 ...

  4. 2020 ICPC EC Final西安现场赛游记

    也不知道从何说起,也不知道会说些什么,最想表达的就是很累很累. 从第一天去的时候满怀希望,没什么感觉甚至还有一些兴奋.到后来一直在赶路,感觉很疲惫,热身赛的时候觉得马马虎虎,导致热身赛被咕.然后教练就 ...

  5. Serverless实践-静态网站托管

    Serverless实践-静态网站托管 超多图预警!!! 本文旨在帮助不懂运维/网络/服务器知识的小白,在不租用云服务器的情况下,实现Web站点的上线部署 适合边看文章边跟着动手做 包含使用Githu ...

  6. 服务治理演进剖析 & Service Mesh、 xDS核心原理梳理

    基于XDS协议实现控制面板与数据面板通信分享 基于这段时间在同程艺龙基础架构部的蹲坑,聊一聊微服务治理的核心难点.历史演进.最新动态, 以上内容属自我思考,不代表同程艺龙技术水准.如理解有偏差.理解不 ...

  7. Spring context的refresh函数执行过程分析

    今天看了一下Spring Boot的run函数运行过程,发现它调用了Context中的refresh函数.所以先分析一下Spring context的refresh过程,然后再分析Spring boo ...

  8. 探索专有领域的端到端ASR解决之道

    摘要:本文从<Shallow-Fusion End-to-End Contextual Biasing>入手,探索解决专有领域的端到端ASR. 本文分享自华为云社区<语境偏移如何解决 ...

  9. QTableWidget - 基础讲解(2) 样式、右键菜单、表头塌陷、多选等

    转载:https://www.cnblogs.com/zhoug2020/p/3789076.html 在Qt的开发过程中,时常会用到表单(QTableWidget)这个控件,网上的资料不少,但是都是 ...

  10. Mysql_源码包安装详细过程

    一.mysql安装 1.二进制安装 2.源码包安装 3.rpm包安装 1.源码包安装 1)上传或下载源码包 [root@db02 ~]# rz mysql-5.6.46.tar.gz 2)安装依赖 由 ...