深入理解r2dbc在mysql中的使用
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习数据库相关编程知识。下面本篇文章就来带大家聊聊《深入理解r2dbc在mysql中的使用》,介绍一下mysqlr2dbc,希望对大家的知识积累有所帮助,助力实战开发!
简介
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());</connection>
不同的是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()); </connection>
同样的,我们也支持从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());</connection>
或者下面的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());</connection>
使用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()); </connection>
或者下面的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()); </connection>
执行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 connectionPublisher = connectionFactory.create(); </database></port></host></my-driver>
可以看到,我们只需要在连接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 connectionPublisher = connectionFactory.create(); // Alternative: Creating a Mono using Project Reactor Mono<connection> connectionMono = Mono.from(connectionFactory.create());</connection>
最后, 你也可以直接通过创建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(); </void></connection>
以上就是《深入理解r2dbc在mysql中的使用》的详细内容,更多关于mysql的资料请关注golang学习网公众号!

- 上一篇
- 解决windows service 2012阿里云服务器在搭建mysql时缺少msvcr100.dll文件的问题

- 下一篇
- 浅谈Mysql哪些字段适合建立索引
-
- 柔弱的鸡
- 这篇博文太及时了,好细啊,赞 ??,码住,关注老哥了!希望老哥能多写数据库相关的文章。
- 2023-01-11 00:33:19
-
- 数据库 · MySQL | 2天前 |
- 如何检测电脑是否安装MySQL的5种方法
- 278浏览 收藏
-
- 数据库 · MySQL | 2天前 |
- MySQL分区表查询优化技巧
- 126浏览 收藏
-
- 数据库 · MySQL | 2天前 |
- MySQL建库语句与字符集设置教程
- 414浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- MySQL中AS别名用法详解
- 320浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- MySQL创建带主键的表实例
- 247浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- 主外键关系怎么建立?
- 149浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- MySQL中IF函数使用详解
- 392浏览 收藏
-
- 数据库 · MySQL | 5天前 |
- MySQL中IF函数使用详解
- 268浏览 收藏
-
- 数据库 · MySQL | 5天前 |
- MySQL入门:核心概念与操作全解析
- 162浏览 收藏
-
- 数据库 · MySQL | 5天前 |
- MySQL事务是什么?如何保证数据一致性?
- 349浏览 收藏
-
- 数据库 · MySQL | 6天前 |
- MySQL数据分片实现方法及常见方案解析
- 363浏览 收藏
-
- 数据库 · MySQL | 6天前 |
- MySQL基础:增删改查全教程
- 345浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 515次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- AI Mermaid流程图
- SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
- 812次使用
-
- 搜获客【笔记生成器】
- 搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
- 829次使用
-
- iTerms
- iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
- 848次使用
-
- TokenPony
- TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
- 912次使用
-
- 迅捷AIPPT
- 迅捷AIPPT是一款高效AI智能PPT生成软件,一键智能生成精美演示文稿。内置海量专业模板、多样风格,支持自定义大纲,助您轻松制作高质量PPT,大幅节省时间。
- 801次使用
-
- MySQL主从切换的超详细步骤
- 2023-01-01 501浏览
-
- Mysql-普通索引的 change buffer
- 2023-01-25 501浏览
-
- MySQL高级进阶sql语句总结大全
- 2022-12-31 501浏览
-
- Mysql报错:message from server: * is blocked because of many
- 2023-02-24 501浏览
-
- 腾讯云大佬亲码“redis深度笔记”,不讲一句废话,全是精华
- 2023-02-22 501浏览