Use R2DBC with MySQL database

By | June 25, 2020

Introduction

R2DBC is an asynchronous, non-blocking relational database connection specification. Although some NoSQL database vendors provide reactive database clients for their databases, for most projects, migrating to NoSQL is not an ideal choice. This prompted the birth of a universal, responsive relational database connection specification. As a relational database with a huge user base, MySQL also has a reactive drive, but it is not official. However, Spring officially included it in the dependency pool, indicating that the library’s quality is not low. So try it today and try using R2DBC to connect to MySQL.

Dependencies

Based on Spring Boot 2.3.1 and Spring Data R2DBC, as well as the reactive Web framework Webflux, but also depends on the r2dbc-mysql library, all Maven dependencies are:
        <dependency>
            <groupId>dev.miku</groupId>
            <artifactId>r2dbc-mysql</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
The MySQL version is 5.7, and no other version has been tested.

R2DBC configuration

All R2DBC automatic configuration is under the org.springframework.boot.autoconfigure.data.r2dbc package. If you want to configure MySQL, you must configure the corresponding connection factory interface ConnectionFactory, of course, you can also configure it through application.yml.
@Bean
ConnectionFactory connectionFactory() {
    return MySqlConnectionFactory.from(MySqlConnectionConfiguration.builder()
            .host("127.0.0.1")
            .port(3306)
            .username("root")
            .password("00000000")
            .database("db_name")
            .build());
}
When the ConnectionFactory is configured, it will be injected into the DatabaseClient object. This object is non-blocking and is used to execute database reactive client calls and reactive backpressure requests. We can operate the database reactively through this interface.