03:WebFlux Web CRUD 實(shí)踐
前言
上一篇基于功能性端點(diǎn)去創(chuàng)建一個(gè)簡單服務(wù),實(shí)現(xiàn)了 Hello 然评。這一篇用 Spring Boot WebFlux 的注解控制層技術(shù)創(chuàng)建一個(gè) CRUD WebFlux 應(yīng)用节预,讓開發(fā)更方便叶摄。這里我們不對數(shù)據(jù)庫儲存進(jìn)行訪問,因?yàn)楹罄m(xù)會講到安拟,而且這里主要是講一個(gè)完整的 WebFlux CRUD蛤吓。
結(jié)構(gòu)
這個(gè)工程會對城市(City)進(jìn)行管理實(shí)現(xiàn) CRUD 操作。該工程創(chuàng)建編寫后糠赦,得到下面的結(jié)構(gòu)柱衔,其目錄結(jié)構(gòu)如下:
├── pom.xml
├── src
│ └── main
│ ├── java
│ │ └── org
│ │ └── spring
│ │ └── springboot
│ │ ├── Application.java
│ │ ├── dao
│ │ │ └── CityRepository.java
│ │ ├── domain
│ │ │ └── City.java
│ │ ├── handler
│ │ │ └── CityHandler.java
│ │ └── webflux
│ │ └── controller
│ │ └── CityWebFluxController.java
│ └── resources
│ └── application.properties
└── target
如目錄結(jié)構(gòu)樊破,我們需要編寫的內(nèi)容按順序有:
- 對象
- 數(shù)據(jù)訪問層類 Repository
- 處理器類 Handler
- 控制器類 Controller
對象
新建包 org.spring.springboot.domain ,作為編寫城市實(shí)體對象類唆铐。新建城市(City)對象 City哲戚,代碼如下:
/**
* 城市實(shí)體類
*
*/
public class City {
/**
* 城市編號
*/
private Long id;
/**
* 省份編號
*/
private Long provinceId;
/**
* 城市名稱
*/
private String cityName;
/**
* 描述
*/
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProvinceId() {
return provinceId;
}
public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
城市包含了城市編號、省份編號艾岂、城市名稱和描述顺少。具體開發(fā)中,會使用 Lombok 工具來消除冗長的 Java 代碼王浴,尤其是 POJO 的 getter / setter 方法脆炎。具體查看 Lombok 官網(wǎng)地址:projectlombok.org。
數(shù)據(jù)訪問層 CityRepository
新建包 org.spring.springboot.dao 氓辣,作為編寫城市數(shù)據(jù)訪問層類 Repository秒裕。新建 CityRepository,代碼如下:
import org.spring.springboot.domain.City;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
@Repository
public class CityRepository {
private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>();
private static final AtomicLong idGenerator = new AtomicLong(0);
public Long save(City city) {
Long id = idGenerator.incrementAndGet();
city.setId(id);
repository.put(id, city);
return id;
}
public Collection<City> findAll() {
return repository.values();
}
public City findCityById(Long id) {
return repository.get(id);
}
public Long updateCity(City city) {
repository.put(city.getId(), city);
return city.getId();
}
public Long deleteCity(Long id) {
repository.remove(id);
return id;
}
}
@Repository
用于標(biāo)注數(shù)據(jù)訪問組件钞啸,即 DAO 組件几蜻。實(shí)現(xiàn)代碼中使用名為 repository
的 Map 對象作為內(nèi)存數(shù)據(jù)存儲,并對對象具體實(shí)現(xiàn)了具體業(yè)務(wù)邏輯体斩。CityRepository
負(fù)責(zé)將 Book 持久層(數(shù)據(jù)操作)相關(guān)的封裝組織梭稚,完成新增、查詢絮吵、刪除等操作弧烤。
這里不會涉及到數(shù)據(jù)存儲這塊,具體數(shù)據(jù)存儲會在后續(xù)介紹蹬敲。
處理器類 Handler
新建包 org.spring.springboot.handler 暇昂,作為編寫城市處理器類 CityHandler。新建 CityHandler伴嗡,代碼如下:
import org.spring.springboot.dao.CityRepository;
import org.spring.springboot.domain.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class CityHandler {
private final CityRepository cityRepository;
@Autowired
public CityHandler(CityRepository cityRepository) {
this.cityRepository = cityRepository;
}
public Mono<Long> save(City city) {
return Mono.create(cityMonoSink -> cityMonoSink.success(cityRepository.save(city)));
}
public Mono<City> findCityById(Long id) {
return Mono.justOrEmpty(cityRepository.findCityById(id));
}
public Flux<City> findAllCity() {
return Flux.fromIterable(cityRepository.findAll());
}
public Mono<Long> modifyCity(City city) {
return Mono.create(cityMonoSink -> cityMonoSink.success(cityRepository.updateCity(city)));
}
public Mono<Long> deleteCity(Long id) {
return Mono.create(cityMonoSink -> cityMonoSink.success(cityRepository.deleteCity(id)));
}
}
@Component
泛指組件话浇,當(dāng)組件不好歸類的時(shí)候,使用該注解進(jìn)行標(biāo)注闹究。然后用 final
和 @Autowired
標(biāo)注在構(gòu)造器注入 CityRepository Bean幔崖,代碼如下:
private final CityRepository cityRepository;
@Autowired
public CityHandler(CityRepository cityRepository) {
this.cityRepository = cityRepository;
}
從返回值可以看出,Mono 和 Flux 適用于兩個(gè)場景渣淤,即:
- Mono:實(shí)現(xiàn)發(fā)布者赏寇,并返回 0 或 1 個(gè)元素,即單對象
- Flux:實(shí)現(xiàn)發(fā)布者价认,并返回 N 個(gè)元素嗅定,即 List 列表對象
有人會問,這為啥不直接返回對象用踩,比如返回 City/Long/List渠退。原因是忙迁,直接使用 Flux 和 Mono 是非阻塞寫法,相當(dāng)于回調(diào)方式碎乃。利用函數(shù)式可以減少了回調(diào)蠢终,因此會看不到相關(guān)接口琳猫。這恰恰是 WebFlux 的好處:集合了非阻塞 + 異步俗壹。
Mono
Mono 是什么宾符? 官方描述如下:A Reactive Streams Publisher with basic rx operators that completes successfully by emitting an element, or with an error.
Mono 是響應(yīng)流 Publisher 具有基礎(chǔ) rx 操作符」j可以成功發(fā)布元素或者錯(cuò)誤嵌言。如圖所示:
Mono 常用的方法有:
- Mono.create():使用 MonoSink 來創(chuàng)建 Mono
- Mono.justOrEmpty():從一個(gè) Optional 對象或 null 對象中創(chuàng)建 Mono。
- Mono.error():創(chuàng)建一個(gè)只包含錯(cuò)誤消息的 Mono
- Mono.never():創(chuàng)建一個(gè)不包含任何消息通知的 Mono
- Mono.delay():在指定的延遲時(shí)間之后及穗,創(chuàng)建一個(gè) Mono摧茴,產(chǎn)生數(shù)字 0 作為唯一值
Flux
Flux 是什么? 官方描述如下:A Reactive Streams Publisher with rx operators that emits 0 to N elements, and then completes (successfully or with an error).
Flux 是響應(yīng)流 Publisher 具有基礎(chǔ) rx 操作符埂陆】涟祝可以成功發(fā)布 0 到 N 個(gè)元素或者錯(cuò)誤。Flux 其實(shí)是 Mono 的一個(gè)補(bǔ)充猜惋。如圖所示:
所以要注意:如果知道 Publisher 是 0 或 1 個(gè),則用 Mono培愁。
Flux 最值得一提的是 fromIterable 方法著摔。 fromIterable(Iterable<? extends T> it) 可以發(fā)布 Iterable 類型的元素。當(dāng)然定续,F(xiàn)lux 也包含了基礎(chǔ)的操作:map谍咆、merge、concat私股、flatMap摹察、take,這里就不展開介紹了倡鲸。
控制器類 Controller
Spring Boot WebFlux 開發(fā)中供嚎,不需要配置。Spring Boot WebFlux 可以使用自動配置加注解驅(qū)動的模式來進(jìn)行開發(fā)峭状。
新建包目錄 org.spring.springboot.webflux.controller
克滴,并在目錄中創(chuàng)建名為 CityWebFluxController 來處理不同的 HTTP Restful 業(yè)務(wù)請求。代碼如下:
import org.spring.springboot.domain.City;
import org.spring.springboot.handler.CityHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping(value = "/city")
public class CityWebFluxController {
@Autowired
private CityHandler cityHandler;
@GetMapping(value = "/{id}")
public Mono<City> findCityById(@PathVariable("id") Long id) {
return cityHandler.findCityById(id);
}
@GetMapping()
public Flux<City> findAllCity() {
return cityHandler.findAllCity();
}
@PostMapping()
public Mono<Long> saveCity(@RequestBody City city) {
return cityHandler.save(city);
}
@PutMapping()
public Mono<Long> modifyCity(@RequestBody City city) {
return cityHandler.modifyCity(city);
}
@DeleteMapping(value = "/{id}")
public Mono<Long> deleteCity(@PathVariable("id") Long id) {
return cityHandler.deleteCity(id);
}
}
這里按照 REST 風(fēng)格實(shí)現(xiàn)接口优床。那具體什么是 REST?
REST 是屬于 WEB 自身的一種架構(gòu)風(fēng)格劝赔,是在 HTTP 1.1 規(guī)范下實(shí)現(xiàn)的。Representational State Transfer 全稱翻譯為表現(xiàn)層狀態(tài)轉(zhuǎn)化胆敞。Resource:資源着帽。比如 newsfeed杂伟;Representational:表現(xiàn)形式,比如用JSON仍翰,富文本等赫粥;State Transfer:狀態(tài)變化。通過HTTP 動作實(shí)現(xiàn)歉备。
理解 REST ,要明白五個(gè)關(guān)鍵要素:
- 資源(Resource)
- 資源的表述(Representation)
- 狀態(tài)轉(zhuǎn)移(State Transfer)
- 統(tǒng)一接口(Uniform Interface)
- 超文本驅(qū)動(Hypertext Driven)
6 個(gè)主要特性:
- 面向資源(Resource Oriented)
- 可尋址(Addressability)
- 連通性(Connectedness)
- 無狀態(tài)(Statelessness)
- 統(tǒng)一接口(Uniform Interface)
- 超文本驅(qū)動(Hypertext Driven)
具體這里就不一一展開傅是,詳見 http://www.infoq.com/cn/articles/understanding-restful-style。
請求入?yún)⒗傺颉ilters喧笔、重定向、Conversion龟再、formatting 等知識會和以前 MVC 的知識一樣书闸,詳情見文檔:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html
運(yùn)行工程
一個(gè) CRUD 的 Spring Boot Webflux 工程就開發(fā)完畢了,下面運(yùn)行工程驗(yàn)證下利凑。使用 IDEA 右側(cè)工具欄浆劲,點(diǎn)擊 Maven Project Tab ,點(diǎn)擊使用下 Maven 插件的 install
命令哀澈∨平瑁或者使用命令行的形式,在工程根目錄下割按,執(zhí)行 Maven 清理和安裝工程的指令:
cd springboot-webflux-2-restful
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 中執(zhí)行 Application
類啟動膨报,任意正常模式或者 Debug 模式∈嗜伲可以在控制臺看到成功運(yùn)行的輸出:
... 省略
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 工具现柠,開發(fā)必備。進(jìn)行下面操作:
新增城市信息 POST http://127.0.0.1:8080/city
獲取城市信息列表 GET http://127.0.0.1:8080/city
其他接口就不演示了弛矛。
總結(jié)
這里够吩,探討了 Spring WebFlux 的一些功能,構(gòu)建沒有底層數(shù)據(jù)庫的基本 CRUD 工程丈氓。為了更好的展示了如何創(chuàng)建 Flux 流周循,以及如何對其進(jìn)行操作。下面會講到如何操作數(shù)據(jù)存儲万俗。
本文由博客一文多發(fā)平臺 OpenWrite 發(fā)布鱼鼓!