日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Spring Boot WebFlux-02——WebFlux Web CRUD 实践

發(fā)布時(shí)間:2025/3/19 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot WebFlux-02——WebFlux Web CRUD 实践 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Spring Boot WebFlux-02——WebFlux Web CRUD 實(shí)踐 第02課:WebFlux Web CRUD 實(shí)踐

上一篇基于功能性端點(diǎn)去創(chuàng)建一個(gè)簡(jiǎn)單服務(wù),實(shí)現(xiàn)了 Hello。這一篇用 Spring Boot WebFlux 的注解控制層技術(shù)創(chuàng)建一個(gè) CRUD WebFlux 應(yīng)用,讓開(kāi)發(fā)更方便。這里我們不對(duì)數(shù)據(jù)庫(kù)儲(chǔ)存進(jìn)行訪問(wèn),因?yàn)楹罄m(xù)會(huì)講到,而且這里主要是講一個(gè)完整的 WebFlux CRUD。

結(jié)構(gòu)

這個(gè)工程會(huì)對(duì)城市(City)進(jìn)行管理實(shí)現(xiàn) CRUD 操作。該工程創(chuàng)建編寫(xiě)后,得到下面的結(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),我們需要編寫(xiě)的內(nèi)容按順序有:

  • 對(duì)象
  • 數(shù)據(jù)訪問(wèn)層類(lèi) Repository
  • 處理器類(lèi) Handler
  • 控制器類(lèi) Controller

對(duì)象

新建包 org.spring.springboot.domain,作為編寫(xiě)城市實(shí)體對(duì)象類(lèi)。新建城市(City)對(duì)象 City,代碼如下:

/*** 城市實(shí)體類(lèi)**/ public class City {/** * 城市編號(hào) */ private Long id; /** * 省份編號(hào) */ private Long provinceId; /** * 城市名稱(chēng) */ 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; } }

城市包含了城市編號(hào)、省份編號(hào)、城市名稱(chēng)和描述。具體開(kāi)發(fā)中,會(huì)使用 Lombok 工具來(lái)消除冗長(zhǎng)的 Java 代碼,尤其是 POJO 的 getter / setter 方法,具體查看 Lombok 官網(wǎng)地址

數(shù)據(jù)訪問(wèn)層 CityRepository

新建包 org.spring.springboot.dao,作為編寫(xiě)城市數(shù)據(jù)訪問(wèn)層類(lèi) 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ù)訪問(wèn)組件,即 DAO 組件。實(shí)現(xiàn)代碼中使用名為 repository 的 Map 對(duì)象作為內(nèi)存數(shù)據(jù)存儲(chǔ),并對(duì)對(duì)象具體實(shí)現(xiàn)了具體業(yè)務(wù)邏輯。CityRepository 負(fù)責(zé)將 Book 持久層(數(shù)據(jù)操作)相關(guān)的封裝組織,完成新增、查詢、刪除等操作。

這里不會(huì)涉及到數(shù)據(jù)存儲(chǔ)這塊,具體數(shù)據(jù)存儲(chǔ)會(huì)在后續(xù)介紹。

處理器類(lèi) Handler

新建包 org.spring.springboot.handler,作為編寫(xiě)城市處理器類(lèi) 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)組件不好歸類(lèi)的時(shí)候,使用該注解進(jìn)行標(biāo)注,然后用 final 和 @Autowired 標(biāo)注在構(gòu)造器注入 CityRepository Bean,代碼如下:

private final CityRepository cityRepository;@Autowiredpublic CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }

從返回值可以看出,Mono 和 Flux 適用于兩個(gè)場(chǎng)景,即:

  • Mono:實(shí)現(xiàn)發(fā)布者,并返回 0 或 1 個(gè)元素,即單對(duì)象。
  • Flux:實(shí)現(xiàn)發(fā)布者,并返回 N 個(gè)元素,即 List 列表對(duì)象。

有人會(huì)問(wèn),這為啥不直接返回對(duì)象,比如返回 City/Long/List。原因是,直接使用 Flux 和 Mono 是非阻塞寫(xiě)法,相當(dāng)于回調(diào)方式。利用函數(shù)式可以減少了回調(diào),因此會(huì)看不到相關(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 操作符,可以成功發(fā)布元素或者錯(cuò)誤,如圖所示:

Mono 常用的方法有:

  • Mono.create():使用 MonoSink 來(lái)創(chuàng)建 Mono。
  • Mono.justOrEmpty():從一個(gè) Optional 對(duì)象或 null 對(duì)象中創(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 類(lèi)型的元素。當(dāng)然,Flux 也包含了基礎(chǔ)的操作:map、merge、concat、flatMap、take,這里就不展開(kāi)介紹了。

控制器類(lèi) Controller

Spring Boot WebFlux 開(kāi)發(fā)中,不需要配置。Spring Boot WebFlux 可以使用自動(dòng)配置加注解驅(qū)動(dòng)的模式來(lái)進(jìn)行開(kāi)發(fā)。

新建包目錄 org.spring.springboot.webflux.controller,并在目錄中創(chuàng)建名為 CityWebFluxController 來(lái)處理不同的 HTTP Restful 業(yè)務(wù)請(qǐng)求。代碼如下:

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 全稱(chēng)翻譯為表現(xiàn)層狀態(tài)轉(zhuǎn)化。Resource:資源。比如 newsfeed;Representational:表現(xiàn)形式,比如用 JSON、富文本等;State Transfer:狀態(tài)變化。通過(guò) HTTP 動(dòng)作實(shí)現(xiàn)。

理解 REST,要明白五個(gè)關(guān)鍵要素:

  • 資源(Resource)
  • 資源的表述(Representation)
  • 狀態(tài)轉(zhuǎn)移(State Transfer)
  • 統(tǒng)一接口(Uniform Interface)
  • 超文本驅(qū)動(dòng)(Hypertext Driven)

6 個(gè)主要特性:

  • 面向資源(Resource Oriented)
  • 可尋址(Addressability)
  • 連通性(Connectedness)
  • 無(wú)狀態(tài)(Statelessness)
  • 統(tǒng)一接口(Uniform Interface)
  • 超文本驅(qū)動(dòng)(Hypertext Driven)

具體這里就不一一展開(kāi),詳見(jiàn)這里

請(qǐng)求入?yún)ⅰilters、重定向、Conversion、formatting 等知識(shí)會(huì)和以前 MVC 的知識(shí)一樣,詳情見(jiàn)文檔

運(yùn)行工程

一個(gè) CRUD 的 Spring Boot Webflux 工程就開(kāi)發(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

在控制臺(tái)中看到成功的輸出:

... 省略 [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 類(lèi)啟動(dòng),任意正常模式或者 Debug 模式。可以在控制臺(tái)看到成功運(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)

打開(kāi) POST MAN 工具,開(kāi)發(fā)必備。進(jìn)行下面操作:

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

獲取城市信息列表 GET http://127.0.0.1:8080/city

其他接口就不演示了。

總結(jié)

這里,探討了 Spring WebFlux 的一些功能,構(gòu)建沒(méi)有底層數(shù)據(jù)庫(kù)的基本 CRUD 工程。為了更好的展示了如何創(chuàng)建 Flux 流,以及如何對(duì)其進(jìn)行操作,下篇內(nèi)容會(huì)講到如何操作數(shù)據(jù)存儲(chǔ)。

posted on 2018-07-15 22:45 limuma 閱讀(...) 評(píng)論(...) 編輯 收藏

轉(zhuǎn)載于:https://www.cnblogs.com/limuma/p/9315343.html

總結(jié)

以上是生活随笔為你收集整理的Spring Boot WebFlux-02——WebFlux Web CRUD 实践的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。