1. Introduction
Introduced in March, R2DBC is an asynchronous, non-blocking, relational database connection specification. Although some NoSQL database vendors provide reactive database clients for their databases, moving to NoSQL is not an ideal option for most projects. This led to the creation of a general specification for reactive relational database connections. MySQL, a relational database with a large user base, also has a reaction driver, though it is not official. But Spring officially includes it in the dependency pool, indicating that the quality of the library is not low. So give it a try today and use R2DBC to connect to MySQL.
2. Environment dependence
Based on Spring Boot 2.3.1 and Spring Data R2DBC, as well as reactive Web framework Webflux, but also depends on r2DB-mysql library, all Maven dependencies are:
<! - r2dbc mysql library - >
<dependency>
<groupId>dev.miku</groupId>
<artifactId>r2dbc-mysql</artifactId>
</dependency>
<! Spring R2DBC Abstraction Layer -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<! -- An embedded database type object for automatic configuration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<! Reactive Web Framework -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Copy the code
MySQL version 5.7, no other versions are tested.
3. R2DBC configuration
All R2DBC automatic configuration in org. Springframework. Boot. Autoconfigure. Data. R2DBC package, if you want to configure the MySQL must be targeted ConnectionFactory corresponding connection factory configuration interface, It can also be configured via application.yml. Personally, I like JavaConfig.
@Bean
ConnectionFactory connectionFactory(a) {
return MySqlConnectionFactory.from(MySqlConnectionConfiguration.builder()
.host("127.0.0.1")
.port(3306)
.username("root")
.password("123456")
.database("database_name")
// Additional non-mandatory parameters are omitted
.build());
}
Copy the code
For details about the configuration, see the official description of r2DBC -mysql: github.com/mirromutth/…
When ConnectionFactory is configured, it is injected into the DatabaseClient object. This object is non-blocking and is used to perform database reactive client calls and reaction flow backpressure requests. We can operate the database through this interface in a reactive manner.
4. Write the reaction interface
Let’s create a table and write some data:
create table client_user
(
user_id varchar(64) not null comment 'User Unique Identifier' primary key,
username varchar(64) null comment 'name',
phone_number varchar(64) null comment 'Mobile phone Number',
gender tinyint(1) default 0 null comment '0 Unknown 1 male 2 female '
)
Copy the code
The corresponding entities are:
package cn.felord.r2dbc.config;
import lombok.Data;
/ * * *@author felord.cn
*/
@Data
public class ClientUser {
private String userId;
private String username;
private String phoneNumber;
private Integer gender;
}
Copy the code
Then we write a reaction interface for Webflux:
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
* @since17:7 * /
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private DatabaseClient databaseClient;
/** ** query **@returnReturns the Flux sequence containing all clientusers */
@GetMapping("/get")
public Flux<ClientUser> clientUserFlux(a) {
return databaseClient.execute("select * from client_user").as(ClientUser.class)
.fetch()
.all();
}
/** * responsive write. **@returnThe Mono object contains the number of successful updates */
@GetMapping("/add")
public Mono<Integer> insert(a) {
ClientUser clientUser = new ClientUser();
clientUser.setUserId("34345514644");
clientUser.setUsername("felord.cn");
clientUser.setPhoneNumber("3456121");
clientUser.setGender(1);
returndatabaseClient.insert().into(ClientUser.class) .using(clientUser) .fetch().rowsUpdated(); }}Copy the code
Calling the interface gets the desired data result.
5. To summarize
R2DBC is not as difficult as it might seem at first glance, but it indirectly requires understanding abstract concepts such as Flux and Mono. At the same time, there is no use scenario if it doesn’t work with the Webflux framework. As far as this article’s MySQL is concerned, the R2DBC driver is still community-maintained (I have to say PgSQL does a pretty good job).
But what you need to see is that the equation is the future. If you want to seize the future, you need to know something about it now. This reminds me of what Spring Boot was like five years ago. In addition, there is a Spring official PPT about R2DBC, which is also the authoritative information for you to better understand R2DBC. Can pay attention to: code farmer small fat brother reply R2DBC get.