r2dbc整合
什么是r2dbc
反应式关系数据库连接(R2DBC)项目为关系数据库带来了反应式编程API。
基于Reactive Streams规范。R2DBC建立在Reactive Streams规范之上,它提供了一个完全反应式的非阻塞API。
r2dbc 官网:https://r2dbc.io/
github: r2dbc-mysql 版本
spring-data r2dbc
版本选择
参考下表来确定适合你的项目的r2 dbc-mysql版本。
| spring-boot-starter-data-r2dbc | spring-data-r2dbc | r2dbc-spi | r2dbc-mysql(recommended) |
|---|---|---|---|
| 3.0.* and above | 3.0.* and above | 1.0.0.RELEASE | io.asyncer:r2dbc-mysql:1.2.0 |
| 2.7.* | 1.5.* | 0.9.1.RELEASE | io.asyncer:r2dbc-mysql:0.9.7 |
| 2.6.* and below | 1.4.* and below | 0.8.6.RELEASE | dev.miku:r2dbc-mysql:0.8.2 |
简单试用
<!-- https://mvnrepository.com/artifact/dev.miku/r2dbc-mysql -->
<dependency>
<groupId>dev.miku</groupId>
<artifactId>r2dbc-mysql</artifactId>
<version>0.8.2.RELEASE</version>
</dependency>
@Test
void connection() throws IOException {
// r2dbc基于全异步、响应式、消息驱动
// jdbc:mysql://localhost:3306/test
// r2dbc:mysql://localhost:3306/test
//0、MySQL配置
MySqlConnectionConfiguration configuration = MySqlConnectionConfiguration.builder()
.host("192.168.xx.xx")
.port(3306)
.username("root")
.password("123456")
.database("test")
.connectTimeout(Duration.ofSeconds(3))
.build();
//1、获取连接工厂
MySqlConnectionFactory connectionFactory = MySqlConnectionFactory.from(configuration);
//2、获取到连接,发送sql
Mono<Connection> connectionMono = Mono.from(connectionFactory.create());
// JDBC: Statement: 封装sql的
//3、数据发布者
connectionMono.flatMapMany(connection ->
connection
// .createStatement("INSERT INTO `t_book` (`publisher`, `author`) VALUES ('who', '1')")
.createStatement("select * from t_book where id=?id and publisher=?")
.bind("id", 1L) //具名参数
.bind(1, "pub")
.execute()
).flatMap(result -> {
// 不同版本,api有所不一致
return result.map((readable,book)->{
System.out.println("readable:"+readable);
System.out.println("book:"+book);
Long id = readable.get("id", Long.class);
String publisher = readable.get("publisher", String.class);
Long author = readable.get("author", Long.class);
return new

最低0.47元/天 解锁文章
688

被折叠的 条评论
为什么被折叠?



