深入理解r2dbc在mysql中的使用

简介

mysql应该是我们在日常工作中使用到的一个非常普遍的数据库,虽然mysql现在是oracle公司的,但是它是开源的,市场占有率还是非常高的。

今天我们将会介绍r2dbc在mysql中的使用。

r2dbc-mysql的maven依赖

要想使用r2dbc-mysql,我们需要添加如下的maven依赖:

<dependency>
  <groupId>dev.miku</groupId>
  <artifactId>r2dbc-mysql</artifactId>
  <version>0.8.2.RELEASE</version>
</dependency>

当然,如果你想使用snapshot版本的话,可以这样:

<dependency>
  <groupId>dev.miku</groupId>
  <artifactId>r2dbc-mysql</artifactId>
  <version>${r2dbc-mysql.version}.BUILD-SNAPSHOT</version>
</dependency>

<repository>
  <id>sonatype-snapshots</id>
  <name>SonaType Snapshots</name>
  <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  <snapshots>
    <enabled>true</enabled>
  </snapshots>
</repository>

创建connectionFactory

创建connectionFactory的代码实际上使用的r2dbc的标准接口,所以和之前讲到的h2的创建代码基本上是一样的:

// Notice: the query string must be URL encoded
ConnectionFactory connectionFactory = ConnectionFactories.get(
  "r2dbcs:mysql://root:database-password-in-here@127.0.0.1:3306/r2dbc?" +
  "zeroDate=use_round&" +
  "sslMode=verify_identity&" +
  "useServerPrepareStatement=true&" +
  "tlsVersion=TLSv1.3%2CTLSv1.2%2CTLSv1.1&" +
  "sslCa=%2Fpath%2Fto%2Fmysql%2Fca.pem&" +
  "sslKey=%2Fpath%2Fto%2Fmysql%2Fclient-key.pem&" +
  "sslCert=%2Fpath%2Fto%2Fmysql%2Fclient-cert.pem&" +
  "sslKeyPassword=key-pem-password-in-here"
)

// Creating a Mono using Project Reactor
Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

不同的是ConnectionFactories传入的参数不同。

我们也支持unix domain socket的格式:

// Minimum configuration for unix domain socket
ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:mysql://root@unix?unixSocket=%2Fpath%2Fto%2Fmysql.sock")

Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

同样的,我们也支持从ConnectionFactoryOptions中创建ConnectionFactory:

ConnectionFactoryOptions options = ConnectionFactoryOptions.builder()
  .option(DRIVER, "mysql")
  .option(HOST, "127.0.0.1")
  .option(USER, "root")
  .option(PORT, 3306) // optional, default 3306
  .option(PASSWORD, "database-password-in-here") // optional, default null, null means has no password
  .option(DATABASE, "r2dbc") // optional, default null, null means not specifying the database
  .option(CONNECT_TIMEOUT, Duration.ofSeconds(3)) // optional, default null, null means no timeout
  .option(SSL, true) // optional, default sslMode is "preferred", it will be ignore if sslMode is set
  .option(Option.valueOf("sslMode"), "verify_identity") // optional, default "preferred"
  .option(Option.valueOf("sslCa"), "/path/to/mysql/ca.pem") // required when sslMode is verify_ca or verify_identity, default null, null means has no server CA cert
  .option(Option.valueOf("sslCert"), "/path/to/mysql/client-cert.pem") // optional, default null, null means has no client cert
  .option(Option.valueOf("sslKey"), "/path/to/mysql/client-key.pem") // optional, default null, null means has no client key
  .option(Option.valueOf("sslKeyPassword"), "key-pem-password-in-here") // optional, default null, null means has no password for client key (i.e. "sslKey")
  .option(Option.valueOf("tlsVersion"), "TLSv1.3,TLSv1.2,TLSv1.1") // optional, default is auto-selected by the server
  .option(Option.valueOf("sslHostnameVerifier"), "com.example.demo.MyVerifier") // optional, default is null, null means use standard verifier
  .option(Option.valueOf("sslContextBuilderCustomizer"), "com.example.demo.MyCustomizer") // optional, default is no-op customizer
  .option(Option.valueOf("zeroDate"), "use_null") // optional, default "use_null"
  .option(Option.valueOf("useServerPrepareStatement"), true) // optional, default false
  .option(Option.valueOf("tcpKeepAlive"), true) // optional, default false
  .option(Option.valueOf("tcpNoDelay"), true) // optional, default false
  .option(Option.valueOf("autodetectExtensions"), false) // optional, default false
  .build();
ConnectionFactory connectionFactory = ConnectionFactories.get(options);

// Creating a Mono using Project Reactor
Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

或者下面的unix domain socket格式:

// Minimum configuration for unix domain socket
ConnectionFactoryOptions options = ConnectionFactoryOptions.builder()
  .option(DRIVER, "mysql")
  .option(Option.valueOf("unixSocket"), "/path/to/mysql.sock")
  .option(USER, "root")
  .build();
ConnectionFactory connectionFactory = ConnectionFactories.get(options);

Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

使用MySqlConnectionFactory创建connection

上面的例子中,我们使用的是通用的r2dbc api来创建connection,同样的,我们也可以使用特有的MySqlConnectionFactory来创建connection:

MySqlConnectionConfiguration configuration = MySqlConnectionConfiguration.builder()
  .host("127.0.0.1")
  .user("root")
  .port(3306) // optional, default 3306
  .password("database-password-in-here") // optional, default null, null means has no password
  .database("r2dbc") // optional, default null, null means not specifying the database
  .serverZoneId(ZoneId.of("Continent/City")) // optional, default null, null means query server time zone when connection init
  .connectTimeout(Duration.ofSeconds(3)) // optional, default null, null means no timeout
  .sslMode(SslMode.VERIFY_IDENTITY) // optional, default SslMode.PREFERRED
  .sslCa("/path/to/mysql/ca.pem") // required when sslMode is VERIFY_CA or VERIFY_IDENTITY, default null, null means has no server CA cert
  .sslCert("/path/to/mysql/client-cert.pem") // optional, default has no client SSL certificate
  .sslKey("/path/to/mysql/client-key.pem") // optional, default has no client SSL key
  .sslKeyPassword("key-pem-password-in-here") // optional, default has no client SSL key password
  .tlsVersion(TlsVersions.TLS1_3, TlsVersions.TLS1_2, TlsVersions.TLS1_1) // optional, default is auto-selected by the server
  .sslHostnameVerifier(MyVerifier.INSTANCE) // optional, default is null, null means use standard verifier
  .sslContextBuilderCustomizer(MyCustomizer.INSTANCE) // optional, default is no-op customizer
  .zeroDateOption(ZeroDateOption.USE_NULL) // optional, default ZeroDateOption.USE_NULL
  .useServerPrepareStatement() // Use server-preparing statements, default use client-preparing statements
  .tcpKeepAlive(true) // optional, controls TCP Keep Alive, default is false
  .tcpNoDelay(true) // optional, controls TCP No Delay, default is false
  .autodetectExtensions(false) // optional, controls extension auto-detect, default is true
  .extendWith(MyExtension.INSTANCE) // optional, manual extend an extension into extensions, default using auto-detect
  .build();
ConnectionFactory connectionFactory = MySqlConnectionFactory.from(configuration);

// Creating a Mono using Project Reactor
Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

或者下面的unix domain socket方式:

// Minimum configuration for unix domain socket
MySqlConnectionConfiguration configuration = MySqlConnectionConfiguration.builder()
  .unixSocket("/path/to/mysql.sock")
  .user("root")
  .build();
ConnectionFactory connectionFactory = MySqlConnectionFactory.from(configuration);

Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

执行statement

首先看一个简单的不带参数的statement:

connection.createStatement("INSERT INTO `person` (`first_name`, `last_name`) VALUES ('who', 'how')")
  .execute(); // return a Publisher include one Result

然后看一个带参数的statement:

connection.createStatement("INSERT INTO `person` (`birth`, `nickname`, `show_name`) VALUES (?, ?name, ?name)")
  .bind(0, LocalDateTime.of(2019, 6, 25, 12, 12, 12))
  .bind("name", "Some one") // Not one-to-one binding, call twice of native index-bindings, or call once of name-bindings.
  .add()
  .bind(0, LocalDateTime.of(2009, 6, 25, 12, 12, 12))
  .bind(1, "My Nickname")
  .bind(2, "Naming show")
  .returnGeneratedValues("generated_id")
  .execute(); // return a Publisher include two Results.

注意,如果参数是null的话,可以使用bindNull来进行null值的绑定。

接下来我们看一个批量执行的操作:

connection.createBatch()
  .add("INSERT INTO `person` (`first_name`, `last_name`) VALUES ('who', 'how')")
  .add("UPDATE `earth` SET `count` = `count` + 1 WHERE `id` = 'human'")
  .execute(); // return a Publisher include two Results.

执行事务

我们看一个执行事务的例子:

connection.beginTransaction()
  .then(Mono.from(connection.createStatement("INSERT INTO `person` (`first_name`, `last_name`) VALUES ('who', 'how')").execute()))
  .flatMap(Result::getRowsUpdated)
  .thenMany(connection.createStatement("INSERT INTO `person` (`birth`, `nickname`, `show_name`) VALUES (?, ?name, ?name)")
    .bind(0, LocalDateTime.of(2019, 6, 25, 12, 12, 12))
    .bind("name", "Some one")
    .add()
    .bind(0, LocalDateTime.of(2009, 6, 25, 12, 12, 12))
    .bind(1, "My Nickname")
    .bind(2, "Naming show")
    .returnGeneratedValues("generated_id")
    .execute())
  .flatMap(Result::getRowsUpdated)
  .then(connection.commitTransaction());

使用线程池

为了提升数据库的执行效率,减少建立连接的开销,一般数据库连接都会有连接池的概念,同样的r2dbc也有一个叫做r2dbc-pool的连接池。

r2dbc-pool的依赖:

<dependency>
 <groupId>io.r2dbc</groupId>
 <artifactId>r2dbc-pool</artifactId>
 <version>${version}</version>
</dependency>

如果你想使用snapshot版本,也可以这样指定:

<dependency>
 <groupId>io.r2dbc</groupId>
 <artifactId>r2dbc-pool</artifactId>
 <version>${version}.BUILD-SNAPSHOT</version>
</dependency>

<repository>
 <id>spring-libs-snapshot</id>
 <name>Spring Snapshot Repository</name>
 <url>https://repo.spring.io/libs-snapshot</url>
</repository>

看一下怎么指定数据库连接池:

ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:pool:<my-driver>://<host>:<port>/<database>[?maxIdleTime=PT60S[&…]");

Publisher<? extends Connection> connectionPublisher = connectionFactory.create();

可以看到,我们只需要在连接URL上面添加pool这个driver即可。

同样的,我们也可以通过ConnectionFactoryOptions来创建:

ConnectionFactory connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
  .option(DRIVER, "pool")
  .option(PROTOCOL, "postgresql") // driver identifier, PROTOCOL is delegated as DRIVER by the pool.
  .option(HOST, "…")
  .option(PORT, "…")
  .option(USER, "…")
  .option(PASSWORD, "…")
  .option(DATABASE, "…")
  .build());

Publisher<? extends Connection> connectionPublisher = connectionFactory.create();

// Alternative: Creating a Mono using Project Reactor
Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

最后, 你也可以直接通过创建ConnectionPoolConfiguration来使用线程池:

ConnectionFactory connectionFactory = …;

ConnectionPoolConfiguration configuration = ConnectionPoolConfiguration.builder(connectionFactory)
  .maxIdleTime(Duration.ofMillis(1000))
  .maxSize(20)
  .build();

ConnectionPool pool = new ConnectionPool(configuration);

Mono<Connection> connectionMono = pool.create();

// later

Connection connection = …;
Mono<Void> release = connection.close(); // released the connection back to the pool

// application shutdown
pool.dispose();

到此这篇关于深入理解r2dbc在mysql中的使用的文章就介绍到这了,更多相关mysql r2dbc 内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Mysql字符串截取函数SUBSTRING的用法说明

    感觉上MySQL的字符串函数截取字符,比用程序截取(如PHP或JAVA)来得强大,所以在这里做一个记录,希望对大家有用. 函数: 1.从左开始截取字符串 left(str, length) 说明:left(被截取字段,截取长度) 例:select left(content,200) as abstract from my_content_t 2.从右开始截取字符串 right(str, length) 说明:right(被截取字段,截取长度) 例:select right(content,200

  • MySQL 的CASE WHEN 语句使用说明

    mysql数据库中CASE WHEN语句. case when语句,用于计算条件列表并返回多个可能结果表达式之一. CASE 具有两种格式: 简单 CASE 函数将某个表达式与一组简单表达式进行比较以确定结果. CASE 搜索函数计算一组布尔表达式以确定结果. 两种格式都支持可选的 ELSE 参数. 语法简单 CASE 函数: 复制代码 代码如下: CASE input_expression    WHEN when_expression THEN result_expression      

  • MySQL创建用户与授权方法

    注:我的运行环境是widnows xp professional + MySQL5.0 一, 创建用户: 命令:CREATE USER 'username'@'host' IDENTIFIED BY 'password'; 说明:username - 你将创建的用户名, host - 指定该用户在哪个主机上可以登陆,如果是本地用户可用localhost, 如果想让该用户可以从任意远程主机登陆,可以使用通配符%. password - 该用户的登陆密码,密码可以为空,如果为空则该用户可以不需要密码

  • mysql update语句的用法详解

    首先,单表的UPDATE语句: UPDATE [LOW_PRIORITY] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition] [ORDER BY ...] [LIMIT row_count] 其次,多表的UPDATE语句: UPDATE [LOW_PRIORITY] [IGNORE] table_references SET col_name1=expr1 [, col_n

  • mysql中int、bigint、smallint 和 tinyint的区别详细介绍

    最近使用mysql数据库的时候遇到了多种数字的类型,主要有int,bigint,smallint和tinyint.其中比较迷惑的是int和smallint的差别.今天就在网上仔细找了找,找到如下内容,留档做个总结: 使用整数数据的精确数字数据类型. bigint 从 -2^63 (-9223372036854775808) 到 2^63-1 (9223372036854775807) 的整型数据(所有数字).存储大小为 8 个字节. P.S. bigint已经有长度了,在mysql建表中的len

  • mySQL中replace的用法

    mysql replace实例说明: UPDATE tb1 SET f1=REPLACE(f1, 'abc', 'def'); REPLACE(str,from_str,to_str) 在字符串 str 中所有出现的字符串 from_str 均被 to_str替换,然后返回这个字符串 这个函数用来批量替换数据中的非法关键字是很有用的!如下例子: 例1:UPDATE BBSTopic SET tcontents = replace(replace(tcontents,'共产党','') ,'找死'

  • mysql安装图解 mysql图文安装教程(详细说明)

    MySQL5.0版本的安装图解教程是给新手学习的,当前mysql5.0.96是最新的稳定版本. mysql 下载地址 http://www.jb51.net/softs/2193.html 下面的是MySQL安装的图解,用的可执行文件安装的,详细说明了一下!打开下载的mysql安装文件mysql-5.0.27-win32.zip,双击解压缩,运行"setup.exe",出现如下界面 mysql安装图文教程1 mysql安装向导启动,按"Next"继续 mysql图文

  • mysql 添加索引 mysql 如何创建索引

    1.添加PRIMARY KEY(主键索引) mysql>ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` ) 2.添加UNIQUE(唯一索引) mysql>ALTER TABLE `table_name` ADD UNIQUE ( `column` ) 3.添加INDEX(普通索引) mysql>ALTER TABLE `table_name` ADD INDEX index_name ( `column` ) 4.添加FULLTEX

  • 深入理解r2dbc在mysql中的使用

    简介 mysql应该是我们在日常工作中使用到的一个非常普遍的数据库,虽然mysql现在是oracle公司的,但是它是开源的,市场占有率还是非常高的. 今天我们将会介绍r2dbc在mysql中的使用. r2dbc-mysql的maven依赖 要想使用r2dbc-mysql,我们需要添加如下的maven依赖: <dependency> <groupId>dev.miku</groupId> <artifactId>r2dbc-mysql</artifact

  • 深入理解MySQL中MVCC与BufferPool缓存机制

    目录 一.MVCC机制 undo日志版本链与read-view机制 版本链比对规则 二.BufferPool机制 三.总结 一.MVCC机制 MVCC(Multi Version Concurrency Control),MySQL(默认)RR隔离级别就是通过该机制来保证的,对一行数据的读与写两个操作默认是不会通过加锁互斥来保证隔离性的 串行化隔离级别是为了保证较高的隔离性,是通过将所有操作加锁互斥来实现的 MySQL在RC隔离级别和RR隔离级别下都实现了MVCC机制 RC每次查询都会创建一个r

  • Mysql中mvcc各场景理解应用

    目录 前言 场景一 试验步骤 事务A第一步 事务B执行 事务A执行第二步 结果 场景二 试验步骤 事务A第一步 事务B执行 事务A执行第二步 结果 事务A后续步骤 场景三 场景四 事务A第一步 事务B执行 事务A第二步 事务A第三步 事务A第四步 原因 总结 前言 mysql版本为 mysql> select version(); +-----------+ | version() | +-----------+ | 8.0.27 | +-----------+ 1 row in set (0.

  • 一文带你理解MySql中explain结果filtered

    MySql explain语句的返回结果中,filtered字段要怎么理解? MySql5.7官方文档中描述如下: The filtered column indicates an estimated percentage of table rows filtered by the table condition. The maximum value is 100, which means no filtering of rows occurred. Values decreasing from

  • MySQL中 LBCC 和 MVCC 的理解及常见问题示例

    目录 1. 事务 2. MVCC初探 3. LBCC & MVCC 总结 1. 事务 介绍MVCC之前,先介绍下事务:事务是为了保证数据库中数据的完整性和一致性. 事务的4个基本要素: 原子性(Atomicity):要么同时成功,要么同时失败.(通过undo log回滚日志实现) 一致性(Consistency):一方扣款 xxx 元,另一方收款 xxx 元,符合事物发展的正常逻辑(通过lock锁实现) 隔离性(Isolation):此时有多个类似 扣款/收款 事件同时发生,每个事件之间是相互独

  • MySQL中对于NULL值的理解和使用教程

    NULL值的概念是造成SQL的新手的混淆的普遍原因,他们经常认为NULL是和一个空字符串''的一样的东西.不是这样的!例如,下列语句是完全不同的: mysql> INSERT INTO my_table (phone) VALUES (NULL); mysql> INSERT INTO my_table (phone) VALUES (""); 两个语句把值插入到phone列,但是第一个插入一个NULL值而第二个插入一个空字符串.第一个的含义可以认为是"电话号码不

  • MySQL中group_concat函数深入理解

    本文通过实例介绍了MySQL中的group_concat函数的使用方法,比如select group_concat(name) . MySQL中group_concat函数 完整的语法如下: group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符']) 基本查询 mysql> select * from aa; +------+------+ | id| name | +------+------+ |1 |

  • 深入理解MySQL中的事务机制

    使用数据库事务可以确保除事务性单元内的所有操作都成功完成.MySQL中的InnoDB引擎的表才支持transaction.在一个事务里,如果出现一个数据库操作失败了,事务内的所有操作将被回滚,数据库将会回到事务前的初始状态.有一些不能被回滚的语句:将在本文的最后讨论. 在一个web应用中,会很经常遇到需要使用事务的地方,要么希望若干语句都执行成功,要么都不执行,如果出现有些执行成功,而其他的失败将会导致数据损坏. 在这篇文章的例子中,我们使用下面的两张表"employee"和"

  • Mysql中explain作用详解

    一.MYSQL的索引 索引(Index):帮助Mysql高效获取数据的一种数据结构.用于提高查找效率,可以比作字典.可以简单理解为排好序的快速查找的数据结构. 索引的作用:便于查询和排序(所以添加索引会影响where 语句与 order by 排序语句). 在数据之外,数据库还维护着满足特定查找算法的数据结构,这些数据结构以某种方式引用数据.这样就可以在这些数据结构上实现高级查找算法.这些数据结构就是索引. 索引本身也很大,不可能全部存储在内存中,所以索引往往以索引文件的形式存储在磁盘上. 我们

  • MySQL中基本的多表连接查询教程

    一.多表连接类型 1. 笛卡尔积(交叉连接) 在MySQL中可以为CROSS JOIN或者省略CROSS即JOIN,或者使用','  如: 由于其返回的结果为被连接的两个数据表的乘积,因此当有WHERE, ON或USING条件的时候一般不建议使用,因为当数据表项目太多的时候,会非常慢.一般使用LEFT [OUTER] JOIN或者RIGHT [OUTER] JOIN 2.   内连接INNER JOIN 在MySQL中把I SELECT * FROM table1 CROSS JOIN tabl

随机推荐