1. Introduction
It was introduced in March R2DBC , which is an asynchronous, non blocking relational database connection specification. Although some NoSQL database vendors provide reactive database clients for their databases, migration to NoSQL is not an ideal choice for most projects. This promotes the birth of a general responsive relational database connection specification. MySQL, as a relational database with a large user base, also has a reactive driver, but it is not official. However, Spring officially included it in the dependency pool, indicating that the quality of the class library is not low. So today, try R2DBC to connect MySQL.
2. Environmental dependence
Based on Spring Boot 2.3.1 and Spring Data R2DBC, there is also a reactive Web framework, Webflux, which also relies on the r2dbc MySQL library. All Maven depends on:
<!--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 to be introduced for automatic configuration--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <!--Reaction web frame--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
MySQL version is 5.7, no other version has been tested.
3. R2DBC configuration
All R2DBC auto configurations are in the org.springframework.boot . autoconfigure.data Under the. R2DBC package, if you want to configure MySQL, you must specifically configure the corresponding connection factory interface ConnectionFactory. Of course, you can also use the application.yml to configure. I prefer JavaConfig.
@Bean ConnectionFactory connectionFactory() { return MySqlConnectionFactory.from(MySqlConnectionConfiguration.builder() .host("127.0.0.1") .port(3306) .username("root") .password("123456") .database("database_name") // Additional optional parameters are omitted .build()); }
For detailed configuration, please refer to the official instructions of r2dbc MySQL: https://github.com/mirromutth/r2dbc-mysql
When the ConnectionFactory is configured, it is injected into the DatabaseClient object. The object is non blocking and is used to perform database reactive client calls and reactive flow back pressure requests. We can use this interface to operate the database in a reactive way.
4. Write reactive interface
Let's first create a table and write some data:
create table client_user ( user_id varchar(64) not null comment 'User unique identification' primary key, username varchar(64) null comment 'name', phone_number varchar(64) null comment 'cell-phone number', gender tinyint(1) default 0 null comment '0 Unknown 1 male 2 female ' )
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; }
Then we write a reactive interface of 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 * @since 17 :07 */ @RestController @RequestMapping("/user") public class UserController { @Resource private DatabaseClient databaseClient; /** * query * * @return Return Flux sequence containing all clientusers */ @GetMapping("/get") public Flux<ClientUser> clientUserFlux() { return databaseClient.execute("select * from client_user").as(ClientUser.class) .fetch() .all(); } /** * Reactive write * * @return Mono Object contains the number of successful updates */ @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(); } }
Call the interface to get the expected data results.
5. Summary
At first glance, R2DBC is not as difficult as you think, but indirectly you need to understand such abstract concepts as Flux and Mono. At the same time, at present, there is no use scenario if it does not cooperate with the Webflux framework. As far as MySQL in this article is concerned, R2DBC driver or community maintenance (I have to say that PgSQL does a good job).
What you need to see, however, is that reaction is the future. If you want to grasp the future, you need to know something about it now. This reminds me of the feeling that I just touched Spring Boot five years ago. In addition, here is an official Spring PPT about r2dbc, which is also the authoritative information for you to better understand r2dbc. You can pay attention to: the little fatty brother of minong replies to r2dbc to get it.
Pay attention to the official account: Felordcn for more information