WebFlux 集成 Thymeleaf 、 Mongodb 实践 - Spring Boot(六)
这是泥瓦匠的第105篇原创
文章工程:
- JDK 1.8
- Maven 3.5.2
- Spring Boot 2.1.3.RELEASE
- 工程名:springboot-webflux-5-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 都行。
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
系列教程目录
- 《01:WebFlux 系列教程大纲》
- 《02:WebFlux 快速入门实践》
- 《03:WebFlux Web CRUD 实践》
- 《04:WebFlux 整合 Mongodb》
- 《05:WebFlux 整合 Thymeleaf》
- 《06:WebFlux 中 Thymeleaf 和 Mongodb 实践》
- 《07:WebFlux 整合 Redis》
- 《08:WebFlux 中 Redis 实现缓存》
- 《09:WebFlux 中 WebSocket 实现通信》
- 《10:WebFlux 集成测试及部署》
- 《11:WebFlux 实战图书管理系统》
代码示例
本文示例读者可以通过查看下面仓库的中的模块工程名: 2-x-spring-boot-webflux-handling-errors:
- Github:https://github.com/JeffLi1993/springboot-learning-example
- Gitee:https://gitee.com/jeff1993/springboot-learning-example
如果您对这些感兴趣,欢迎 star、follow、收藏、转发给予支持!
参考资料
- Spring Boot 2.x WebFlux 系列:https://www.bysocket.com/archives/2290
- spring.io 官方文档
WebFlux 集成 Thymeleaf 、 Mongodb 实践 - Spring Boot(六)的更多相关文章
- 《深入实践Spring Boot》阅读笔记之一:基础应用开发
上上篇「1718总结与计划」中提到,18年要对部分项目拆分,进行服务化,并对代码进行重构.公司技术委员会也推荐使用spring boot,之前在各个技术网站中也了解过,它可以大大简化spring配置和 ...
- 《深入实践Spring Boot》阅读笔记之二:分布式应用开发
上篇文章总结了<深入实践Spring Boot>的第一部分,这篇文章介绍第二部分:分布式应用开发,以及怎么构建一个高性能的服务平台. 主要从以下几个方面总结: Spring Boot SS ...
- 《深入实践Spring Boot》阅读笔记之三:核心技术源代码分析
刚关注的朋友,可以回顾前两篇文章: 基础应用开发 分布式应用开发 上篇文章总结了<深入实践Spring Boot>的第二部分,本篇文章总结第三部分,也是最后一部分.这部分主要讲解核心技术的 ...
- Spring Boot(六):如何使用mybatis
Spring Boot(六):如何使用mybatis orm框架的本质是简化编程中操作数据库的编码,发展到现在基本上就剩两家了,一个是宣称可以不用写一句SQL的hibernate,一个是可以灵活调试动 ...
- Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)
号外:为读者持续整理了几份最新教程,覆盖了 Spring Boot.Spring Cloud.微服务架构等PDF.获取方式:关注右侧公众号"泥瓦匠BYSocket",来领取吧! 摘 ...
- Spring Boot实践——Spring Boot 2.0 新特性和发展方向
出自:https://mp.weixin.qq.com/s/EWmuzsgHueHcSB0WH-3AQw 以Java 8 为基准 Spring Boot 2.0 要求Java 版本必须8以上, Jav ...
- 后端开发实践——Spring Boot项目模板
在我的工作中,我从零开始搭建了不少软件项目,其中包含了基础代码框架和持续集成基础设施等,这些内容在敏捷开发中通常被称为"第0个迭代"要做的事情.但是,当项目运行了一段时间之后再来反 ...
- Thymeleaf 模板 在spring boot 中的引用和应用
Thymeleaf是一个java类库,他是一个xml/xhtml/html5的模板引擎和Struts框架的freemarker模板类似,可以作为mvc的web应用的view层. Thymeleaf还提 ...
- 使用MongoDB的Spring Boot和MongoTemplate教程
在本教程中,我们将构建一个Spring Boot应用程序,该应用程序演示如何使用MongoTemplate API访问MongoDB数据库中的数据. 对于MongoDB,我们将使用mLab,它提供了M ...
随机推荐
- java多线程模拟生产者消费者问题,公司面试常常问的题。。。
package com.cn.test3; //java多线程模拟生产者消费者问题 //ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品 // ...
- 在.net core的web项目中使用kindeditor
本项目是一个.net core的mvc项目 1.下载kindeditor 4.1.11 解压后将文件夹置于 wwwroot目录下,如图: 2.在HomeController的Index控制器对应的in ...
- WinEdt && LaTex(五)—— 内容的排版
1. 无序列表 需要的环境是\begin{itemize} \end{itemize} \begin{itemize} \item hello \item world \end{itemize} 2. ...
- Oracle实践--PL/SQL综合之分页存储过程
Oracle PL/SQL分页的存储过程 Oracle,分页,存储过程三个词结合起来,来个综合点的小练习,运用之前的PL/SQL创建一个分页的存储过程,仅仅须要简单几步就可以. 1.声明一个引用游标 ...
- 怎样从一名程序员过度到项目经理(整理自csdn论坛) 选择自 whoopee 的 Blog
1.从程序员到PM,是一条脱变的路,事实上程序员走的路最终不应该是项目经理.首先有一点需要明白的就是,一定规模的项目中,项目经理不需要太懂技术,他可以是一知半解.项目经理的任务不是在技术方面,技术相关 ...
- jquery layer插件弹出弹层 结构紧凑,功能强大
/* 去官方网站下载最新的js http://sentsin.com/jquery/layer/ ①引用jquery ②引用layer.min.js */ 事件触发炸弹层可以自由绑定,例如: $('# ...
- PostgreSQL9.3:JSON 功能增强 根据PQ中文论坛francs 给出的东西结合自己的摸索总结下
在 PostgreSQL 9.2 版本中已经支持 JSON 类型,不过支持的操作非常有限,仅支持以下函数 array_to_json(anyarray [, pretty_bool]) row_ ...
- c# 编写REST的WCF
REST(Representational State Transfer)即 表述性状态传递 ,简称REST,通俗来讲就是:资源在网络中以某种表现形式进行状态转移. RESTful是一种软件架构风格. ...
- Qt之自定义搜索框——QLineEdit里增加一个Layout,还不影响正常输入文字(好像是一种比较通吃的方法)
简述 关于搜索框,大家都经常接触.例如:浏览器搜索.Windows资源管理器搜索等. 当然,这些对于Qt实现来说毫无压力,只要思路清晰,分分钟搞定. 方案一:调用QLineEdit现有接口 void ...
- DELPHI编写服务程序总结(在系统服务和桌面程序之间共享内存,在服务中使用COM组件)
DELPHI编写服务程序总结 一.服务程序和桌面程序的区别 Windows 2000/XP/2003等支持一种叫做“系统服务程序”的进程,系统服务和桌面程序的区别是:系统服务不用登陆系统即可运行:系统 ...