使用反應式關係數據庫鏈接規範R2DBC操做MySQL數據庫

1. 簡介

三月份已經介紹過R2DBC,它是一種異步的、非阻塞的關係式數據庫鏈接規範。儘管一些NoSQL數據庫供應商爲其數據庫提供了反應式數據庫客戶端,但對於大多數項目而言,遷移到NoSQL並非一個理想的選擇。這促使了一個通用的響應式關係數據庫鏈接規範的誕生。 做爲擁有龐大用戶羣的關係式數據庫MySQL也有了反應式驅動,不過並非官方的。可是Spring官方將其歸入了依賴池,說明該類庫的質量並不低。因此今天就嚐嚐鮮,試一下使用R2DBC鏈接MySQLhtml

2. 環境依賴

基於Spring Boot 2.3.1Spring Data R2DBC,還有反應式Web框架Webflux,同時也要依賴r2dbc-mysql庫,全部的Maven依賴爲:java

       <!--r2dbc mysql 庫-->
        <dependency>
            <groupId>dev.miku</groupId>
            <artifactId>r2dbc-mysql</artifactId>
        </dependency>
        <!--Spring r2dbc 抽象層-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-r2dbc</artifactId>
        </dependency>
        <!--自動配置須要引入的一個嵌入式數據庫類型對象-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
       <!--反應式web框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

MySQL版本爲5.7,沒有測試其它版本。mysql

3. R2DBC配置

全部的R2DBC自動配置都在org.springframework.boot.autoconfigure.data.r2dbc包下,若是要配置MySQL必須針對性的配置對應的鏈接工廠接口ConnectionFactory,固然也能夠經過application.yml配置。我的比較喜歡JavaConfigreact

@BeanConnectionFactory connectionFactory() {    return MySqlConnectionFactory.from(MySqlConnectionConfiguration.builder()
            .host("127.0.0.1")
            .port(3306)
            .username("root")
            .password("123456")
            .database("database_name")             // 額外的其它非必選參數省略                          
            .build());
}

詳細配置可參考r2dbc-mysql的官方說明:https://github.com/mirromutth/r2dbc-mysqlgit

ConnectionFactory配置好後,就會被注入DatabaseClient 對象。該對象是非阻塞的,用於執行數據庫反應性客戶端調用與反應流背壓請求。咱們能夠經過該接口反應式地操做數據庫。github

4. 編寫反應式接口

咱們先建立一張表並寫入一些數據:web

create table client_user
(
    user_id         varchar(64)                              not null comment '用戶惟一標示' primary key,
    username        varchar(64)                              null comment '名稱',
    phone_number    varchar(64)                              null comment '手機號',
    gender          tinyint(1) default 0                     null comment '0 未知 1 男 2 女  ')

對應的實體爲:鄭州試管嬰兒醫院:http://yyk.39.net/hospital/fc964_detail.htmlspring

package cn.felord.r2dbc.config;import lombok.Data;/**
 * @author felord.cn
 */@Datapublic class ClientUser {    private String userId;    private String username;    private String phoneNumber;    private Integer gender;
}

而後咱們編寫一個Webflux的反應式接口:sql

package cn.felord.r2dbc.config;import org.springframework.data.r2dbc.core.DatabaseClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;import javax.annotation.Resource;/**
 * The type User controller.
 *
 * @author felord.cn
 * @since 17 :07
 */@RestController@RequestMapping("/user")public class UserController {    @Resource
    private DatabaseClient databaseClient;    /**
     * 查詢
     *
     * @return 返回Flux序列 包含全部的ClientUser
     */
    @GetMapping("/get")    public Flux<ClientUser> clientUserFlux() {        return databaseClient.execute("select * from client_user").as(ClientUser.class)
                .fetch()
                .all();
    }    /**
     * 響應式寫入.
     *
     * @return Mono對象包含更新成功的條數
     */
    @GetMapping("/add")    public Mono<Integer> insert() {
        ClientUser clientUser = new ClientUser();
        clientUser.setUserId("34345514644");
        clientUser.setUsername("felord.cn");
        clientUser.setPhoneNumber("3456121");
        clientUser.setGender(1);        return databaseClient.insert().into(ClientUser.class)
                .using(clientUser)
                .fetch().rowsUpdated();
    }

}

調用接口就能獲取到指望的數據結果。數據庫

5. 總結

乍一看R2DBC並無想象中的那麼難,可是間接的須要瞭解FluxMono等抽象概念。同時目前來講若是不和Webflux框架配合也沒有使用場景。就本文的MySQL而言,R2DBC驅動仍是社區維護(不得不說PgSQL就作的很好)。鄭州不孕不育醫院:http://jbk.39.net/yiyuanzaixian/zztjyy/

然而須要你看清的是反應式纔是將來。若是你要抓住將來就須要如今就瞭解一些相關的知識。這讓我想起五年前剛剛接觸Spring Boot的感受。另外這裏有一份Spring官方關於R2DBC的PPT,也是讓你更好了解R2DBC的權威資料。

相關文章
相關標籤/搜索