Spring Boot WebFlu-05——WebFlux 中 Thymeleaf 和 MongoDB 實踐


第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 

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> 或者 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://localhost:8080/city/getByName?cityName=杭州,可以看到如圖的響應:

file

繼續訪問 http://localhost:8080/city/page/list,發現沒有值,那么按照上一篇的內容插入幾條數據即可有值,如圖:

file

總結

這里初步實現了一個簡單的整合,具體復雜的案例我們在后面的綜合案例中實現,會很酷炫。下面整合 Redis,基於 Redis 可以實現常用的緩存、鎖,下一篇我們將學習如何整合 Reids。

源代碼地址詳見這里 :https://github.com/JeffLi1993/springboot-learning-example


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM