当前位置: 移动技术网 > IT编程>开发语言>Java > WebFlux 集成 Thymeleaf 、 Mongodb 实践 - Spring Boot(六)

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

2019年07月01日  | 移动技术网IT编程  | 我要评论

这是泥瓦匠的第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

file

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

结构

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

file

目录核心如下

  • 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
file

打开浏览器,访问 http://www.lhsxpumps.com/_localhost:8080/city/getbyname?cityname=杭州,可以看到如图的响应:

file

继续访问 http://www.lhsxpumps.com/_localhost:8080/city/page/list , 发现没有值,那么按照上一讲插入几条数据即可有值,如图:

file

总结

这里,初步实现了一个简单的整合,具体复杂的案例我们在综合案例中实现,会很酷炫很适合。下面整合 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:

如果您对这些感兴趣,欢迎 star、follow、收藏、转发给予支持!

参考资料

  • spring boot 2.x webflux 系列:https://www.bysocket.com/archives/2290
  • spring.io 官方文档

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网