├── .gitignore ├── README.md ├── java-agent-example ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── common │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── io │ │ └── r2dbc │ │ └── examples │ │ ├── Application.java │ │ └── agent │ │ ├── ByteBuddyProxyFactory.java │ │ └── R2dbcProxyAgent.java ├── mvnw ├── mvnw.cmd ├── package-agent │ └── pom.xml ├── package-application │ └── pom.xml └── pom.xml └── listener-example ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── images ├── metrics-actuator-connection.png ├── metrics-actuator-transaction.png ├── metrics-jmx-connection.png ├── metrics-jmx-entries.png ├── metrics-jmx-query.png ├── metrics-slow-query-log.png ├── zipkin-span-batch-query.png ├── zipkin-span-connection.png ├── zipkin-span-query.png ├── zipkin-span-transaction.png ├── zipkin-tracing-query.png ├── zipkin-tracing-rollback.png └── zipkin-tracing-transaction.png ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── io │ │ └── r2dbc │ │ └── examples │ │ ├── Application.java │ │ ├── DatabaseClientController.java │ │ ├── MetricsExecutionListener.java │ │ ├── QueryTimeMetricsExecutionListener.java │ │ ├── R2dbcSpiController.java │ │ ├── SpringAopProxyFactory.java │ │ └── TracingExecutionListener.java └── resources │ └── application.yaml └── test └── java └── io └── r2dbc └── examples ├── MetricsExecutionListenerTest.java ├── QueryTimeMetricsExecutionListenerTest.java └── TracingExecutionListenerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | target/ 26 | *.iml 27 | *.ipr 28 | *.iws 29 | .idea/ 30 | 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # r2dbc-proxy-examples 2 | 3 | [r2dbc-proxy][r2dbc-proxy] sample projects. 4 | 5 | ## listener-example 6 | 7 | This example provides sample listener implementations. 8 | Currently, there are listeners that integrate with [Spring Cloud Sleuth][spring-cloud-sleuth] 9 | and [Micrometer][micrometer]. 10 | 11 | Also, this example uses `ProxyFactory` implementation with [Spring's ProxyFactory framework][spring-proxyfactory] 12 | to create proxies. (optional) 13 | 14 | ## java-agent-example 15 | 16 | This example provides sample implementation to apply [r2dbc-proxy][r2dbc-proxy] 17 | using Java Agent. 18 | 19 | With Java Agent, application does NOT need to know or aware of [r2dbc-proxy][r2dbc-proxy]. 20 | So, it is a non-intrusive way to integrate the [r2dbc-proxy][r2dbc-proxy] framework to 21 | the application. 22 | 23 | Also, this uses `ProxyFactory` implementation with [Byte Buddy][byte-buddy] which 24 | performs byte code manipulation to create proxies. (optional) 25 | 26 | ---- 27 | [r2dbc-proxy]: https://github.com/r2dbc/r2dbc-proxy 28 | [spring-cloud-sleuth]: https://spring.io/projects/spring-cloud-sleuth 29 | [micrometer]: http://micrometer.io/ 30 | [byte-buddy]: https://bytebuddy.net 31 | [spring-proxyfactory]: https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-prog 32 | -------------------------------------------------------------------------------- /java-agent-example/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.net.*; 21 | import java.io.*; 22 | import java.nio.channels.*; 23 | import java.util.Properties; 24 | 25 | public class MavenWrapperDownloader { 26 | 27 | /** 28 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 29 | */ 30 | private static final String DEFAULT_DOWNLOAD_URL = 31 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 32 | 33 | /** 34 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 35 | * use instead of the default one. 36 | */ 37 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 38 | ".mvn/wrapper/maven-wrapper.properties"; 39 | 40 | /** 41 | * Path where the maven-wrapper.jar will be saved to. 42 | */ 43 | private static final String MAVEN_WRAPPER_JAR_PATH = 44 | ".mvn/wrapper/maven-wrapper.jar"; 45 | 46 | /** 47 | * Name of the property which should be used to override the default download url for the wrapper. 48 | */ 49 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 50 | 51 | public static void main(String args[]) { 52 | System.out.println("- Downloader started"); 53 | File baseDirectory = new File(args[0]); 54 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 55 | 56 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 57 | // wrapperUrl parameter. 58 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 59 | String url = DEFAULT_DOWNLOAD_URL; 60 | if(mavenWrapperPropertyFile.exists()) { 61 | FileInputStream mavenWrapperPropertyFileInputStream = null; 62 | try { 63 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 64 | Properties mavenWrapperProperties = new Properties(); 65 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 66 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 67 | } catch (IOException e) { 68 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 69 | } finally { 70 | try { 71 | if(mavenWrapperPropertyFileInputStream != null) { 72 | mavenWrapperPropertyFileInputStream.close(); 73 | } 74 | } catch (IOException e) { 75 | // Ignore ... 76 | } 77 | } 78 | } 79 | System.out.println("- Downloading from: : " + url); 80 | 81 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 82 | if(!outputFile.getParentFile().exists()) { 83 | if(!outputFile.getParentFile().mkdirs()) { 84 | System.out.println( 85 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 86 | } 87 | } 88 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 89 | try { 90 | downloadFileFromURL(url, outputFile); 91 | System.out.println("Done"); 92 | System.exit(0); 93 | } catch (Throwable e) { 94 | System.out.println("- Error downloading"); 95 | e.printStackTrace(); 96 | System.exit(1); 97 | } 98 | } 99 | 100 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 101 | URL website = new URL(urlString); 102 | ReadableByteChannel rbc; 103 | rbc = Channels.newChannel(website.openStream()); 104 | FileOutputStream fos = new FileOutputStream(destination); 105 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 106 | fos.close(); 107 | rbc.close(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /java-agent-example/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /java-agent-example/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /java-agent-example/README.md: -------------------------------------------------------------------------------- 1 | # [r2dbc-proxy][r2dbc-proxy] example with Java Agent. 2 | 3 | This sample project contains following implementations. 4 | 5 | `Application.java` is a simple spring-boot web application which uses R2DBC to access 6 | in-memory H2 database. 7 | 8 | `R2dbcProxyAgent` is the java agent implementation that instruments the attached application's 9 | `ConnectionFactory`, and make it participate to `r2dbc-proxy` framework. 10 | Instrumentation uses [Byte Buddy][byte-buddy]. 11 | 12 | When `ConnectionFactory` is instrumented, it prints out method interactions with R2DBC 13 | SPI and query executions to the application console. 14 | 15 | `ByteBuddyProxyFactory` is a `ProxyFactory` implementation that uses [Byte Buddy][byte-buddy] 16 | to create proxy objects. Usage of this class is optional. 17 | 18 | 19 | ## Modules 20 | 21 | ### common 22 | 23 | This module contains implementation for both spring-boot application(`Application`) and 24 | java agent(`R2dbcProxyAgent`) classes. 25 | 26 | ### package-application 27 | 28 | This module generates executable spring-boot jar using `Application` class from common module. 29 | Generated jar file does NOT contain any agent related classes. 30 | 31 | This module does NOT contain any implementation. Simply `pom.xml` is used to generate jar file. 32 | 33 | ### package-agent 34 | 35 | This module generates java agent jar file using `R2dbcProxyAgent` class from common module. 36 | The generated jar contains agent implementation and unpacked related libraries. 37 | 38 | This module does NOT contain any implementation. Simply `pom.xml` is used to generate jar file. 39 | 40 | 41 | ## Build 42 | 43 | ```shell 44 | ./mvnw packagae 45 | ``` 46 | 47 | This generates following files: 48 | 49 | Application: `package-application/target/examples-application-1.0-SNAPSHOT.jar` 50 | _(This is a spring-boot executable jar file.)_ 51 | 52 | Agent: `package-agent/target/examples-agent-1.0-SNAPSHOT-jar-with-dependencies.jar` 53 | 54 | **NOTE** 55 | Currently, it is depending on SNAPSHOT version of r2dbc-proxy. This is because some changesets 56 | after M7 are needed to run the agent with ByteBuddy. Once M8 is released, SNAPSHOT dependency 57 | should be updated. 58 | 59 | ## Run 60 | 61 | ### Command line 62 | 63 | #### Run application only 64 | 65 | ```shell 66 | java -jar package-application/target/examples-application-1.0-SNAPSHOT.jar 67 | ``` 68 | 69 | #### Run application with java agent 70 | 71 | ```shell 72 | java -javaagent:package-agent/target/examples-agent-1.0-SNAPSHOT-jar-with-dependencies.jar \ 73 | -jar package-application/target/examples-application-1.0-SNAPSHOT.jar 74 | ``` 75 | 76 | ### From IDE 77 | 78 | Run `Application` class. 79 | 80 | Once agent jar file has generated by command line, specify the following parameter to 81 | the "VM Options": 82 | 83 | `-javaagent:package-agent/target/examples-agent-1.0-SNAPSHOT-jar-with-dependencies.jar` 84 | 85 | 86 | ## Endpoint 87 | 88 | ```shell 89 | curl -i localhost:8080/ 90 | ``` 91 | 92 | Please reference `Application` to see what URLs are mapped. 93 | 94 | ---- 95 | 96 | [r2dbc-proxy]: https://github.com/r2dbc/r2dbc-proxy 97 | [byte-buddy]: https://bytebuddy.net/ -------------------------------------------------------------------------------- /java-agent-example/common/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | r2dbc-proxy-examples-agent-common 6 | jar 7 | r2dbc-proxy-examples-agent-common 8 | http://maven.apache.org 9 | 10 | 11 | net.ttddyy 12 | r2dbc-proxy-examples-agent-parent 13 | 1.0-SNAPSHOT 14 | ../pom.xml 15 | 16 | 17 | 18 | 19 | 20 | 21 | org.apache.maven.plugins 22 | maven-compiler-plugin 23 | ${compiler.version} 24 | 25 | ${java.version} 26 | ${java.version} 27 | ${java.version} 28 | ${java.version} 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 41 | 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-web 47 | true 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-webflux 52 | true 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-starter-jdbc 57 | true 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-actuator 62 | true 63 | 64 | 65 | 66 | org.springframework.data 67 | spring-data-r2dbc 68 | true 69 | 70 | 71 | 72 | io.r2dbc 73 | r2dbc-h2 74 | true 75 | 76 | 77 | 78 | 79 | 80 | 81 | io.r2dbc 82 | r2dbc-proxy 83 | true 84 | 85 | 86 | 87 | net.bytebuddy 88 | byte-buddy 89 | ${byte-buddy.version} 90 | true 91 | 92 | 93 | net.bytebuddy 94 | byte-buddy-agent 95 | ${byte-buddy.version} 96 | true 97 | 98 | 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /java-agent-example/common/src/main/java/io/r2dbc/examples/Application.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.r2dbc.h2.H2ConnectionConfiguration; 4 | import io.r2dbc.h2.H2ConnectionFactory; 5 | import io.r2dbc.spi.ConnectionFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.data.r2dbc.core.DatabaseClient; 13 | import org.springframework.jdbc.core.JdbcOperations; 14 | import org.springframework.jdbc.core.JdbcTemplate; 15 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 16 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 17 | import org.springframework.transaction.reactive.TransactionalOperator; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | import reactor.core.publisher.Flux; 21 | import reactor.core.publisher.Mono; 22 | 23 | import javax.sql.DataSource; 24 | 25 | /** 26 | * R2DBC proxy sample application 27 | */ 28 | @SpringBootApplication 29 | @RestController 30 | public class Application { 31 | 32 | public static void main(String[] args) { 33 | 34 | // To simply apply the agent implementation, uncomment here 35 | // R2dbcProxyAgent.premain(null, ByteBuddyAgent.install()); 36 | 37 | ApplicationContext ctx = SpringApplication.run(Application.class, args); 38 | 39 | // ctx.getBean(ConnectionFactory.class).getMetadata(); 40 | } 41 | 42 | @Autowired 43 | DatabaseClient databaseClient; 44 | 45 | @Autowired 46 | TransactionalOperator operator; 47 | 48 | @RequestMapping("/") 49 | Flux select() { 50 | return this.databaseClient.execute("SELECT value FROM test;") 51 | .map(row -> row.get("value", Integer.class)) 52 | .all(); 53 | } 54 | 55 | @RequestMapping("/transaction") 56 | Mono transaction() { 57 | return this.databaseClient.execute("INSERT INTO test VALUES (:value)") 58 | .bind("value", 200) 59 | .fetch().rowsUpdated().as(this.operator::transactional); 60 | } 61 | 62 | // TODO: find a way to manually rollback transaction 63 | // @RequestMapping("/rollback") 64 | // Mono rollback() { 65 | // return this.databaseClient.execute("INSERT INTO test VALUES (:value)") 66 | // .bind("value", "ABC") // wrong value type 67 | // .fetch().rowsUpdated().as(this.operator::transactional) 68 | // .onErrorResume(t -> Mono.just(-99)); 69 | // } 70 | 71 | @RequestMapping("/slow") 72 | Flux slow() { 73 | return this.databaseClient.execute("CALL SLEEP(700);").map(row -> Mono.just(-1)).all(); 74 | } 75 | 76 | @Bean 77 | DataSource dataSource() { 78 | return new EmbeddedDatabaseBuilder() 79 | .setType(EmbeddedDatabaseType.H2) 80 | .build(); 81 | } 82 | 83 | @Bean 84 | CommandLineRunner bootstrap(DataSource dataSource) { 85 | return args -> { 86 | JdbcOperations jdbcOperations = new JdbcTemplate(dataSource); 87 | jdbcOperations.execute("DROP TABLE IF EXISTS test"); 88 | jdbcOperations.execute("CREATE TABLE test ( value INTEGER )"); 89 | jdbcOperations.execute("INSERT INTO test VALUES (100)"); 90 | jdbcOperations.execute("INSERT INTO test VALUES (200)"); 91 | 92 | // create sleep function for slow query 93 | jdbcOperations.execute("CREATE ALIAS SLEEP FOR \"java.lang.Thread.sleep(long)\""); 94 | }; 95 | } 96 | 97 | @Bean 98 | ConnectionFactory connectionFactory() { 99 | H2ConnectionConfiguration h2Configuration = H2ConnectionConfiguration.builder() 100 | .username("sa") 101 | .password("") 102 | .inMemory("testdb") 103 | .build(); 104 | 105 | 106 | ConnectionFactory connectionFactory = new H2ConnectionFactory(h2Configuration); 107 | return connectionFactory; 108 | } 109 | 110 | 111 | @Bean 112 | DatabaseClient databaseClient(ConnectionFactory connectionFactory) { 113 | return DatabaseClient.create(connectionFactory); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /java-agent-example/common/src/main/java/io/r2dbc/examples/agent/ByteBuddyProxyFactory.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples.agent; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.Method; 5 | 6 | import io.r2dbc.proxy.callback.BatchCallbackHandler; 7 | import io.r2dbc.proxy.callback.CallbackHandler; 8 | import io.r2dbc.proxy.callback.ConnectionCallbackHandler; 9 | import io.r2dbc.proxy.callback.ConnectionFactoryCallbackHandler; 10 | import io.r2dbc.proxy.callback.ProxyConfig; 11 | import io.r2dbc.proxy.callback.ProxyFactory; 12 | import io.r2dbc.proxy.callback.ResultCallbackHandler; 13 | import io.r2dbc.proxy.callback.StatementCallbackHandler; 14 | import io.r2dbc.proxy.core.ConnectionInfo; 15 | import io.r2dbc.proxy.core.QueryExecutionInfo; 16 | import io.r2dbc.proxy.core.StatementInfo; 17 | import io.r2dbc.spi.Batch; 18 | import io.r2dbc.spi.Connection; 19 | import io.r2dbc.spi.ConnectionFactory; 20 | import io.r2dbc.spi.Result; 21 | import io.r2dbc.spi.Statement; 22 | import net.bytebuddy.ByteBuddy; 23 | import net.bytebuddy.implementation.bind.annotation.AllArguments; 24 | import net.bytebuddy.implementation.bind.annotation.Origin; 25 | import net.bytebuddy.implementation.bind.annotation.RuntimeType; 26 | import net.bytebuddy.implementation.bind.annotation.This; 27 | 28 | import static net.bytebuddy.implementation.MethodDelegation.to; 29 | import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy; 30 | 31 | /** 32 | * {@link ProxyFactory} implementation with {@link ByteBuddy}. 33 | * 34 | * Instead of using JDK Dynamic Proxy, use Byte Buddy to create proxies. 35 | * 36 | * https://github.com/r2dbc/r2dbc-spi/issues/9 37 | * 38 | * @author Tadaya Tsuyukubo 39 | */ 40 | public class ByteBuddyProxyFactory implements ProxyFactory { 41 | 42 | private ProxyConfig proxyConfig; 43 | 44 | private Constructor connectionFactoryProxyConstructor; 45 | 46 | private Constructor connectionProxyConstructor; 47 | 48 | private Constructor batchProxyConstructor; 49 | 50 | private Constructor statementProxyConstructor; 51 | 52 | private Constructor resultProxyConstructor; 53 | 54 | public ByteBuddyProxyFactory(ProxyConfig proxyConfig) { 55 | 56 | this.proxyConfig = proxyConfig; 57 | 58 | ByteBuddy byteBuddy = new ByteBuddy(); 59 | 60 | // generate proxy classes 61 | Class connectionFactoryProxyClass = createProxyClass(byteBuddy, ConnectionFactory.class); 62 | Class connectionProxyClass = createProxyClass(byteBuddy, Connection.class); 63 | Class batchProxyClass = createProxyClass(byteBuddy, Batch.class); 64 | Class statementProxyClass = createProxyClass(byteBuddy, Statement.class); 65 | Class resultProxyClass = createProxyClass(byteBuddy, Result.class); 66 | 67 | // retrieve constructor from generated proxy classes 68 | this.connectionFactoryProxyConstructor = findConstructor(connectionFactoryProxyClass); 69 | this.connectionProxyConstructor = findConstructor(connectionProxyClass); 70 | this.batchProxyConstructor = findConstructor(batchProxyClass); 71 | this.statementProxyConstructor = findConstructor(statementProxyClass); 72 | this.resultProxyConstructor = findConstructor(resultProxyClass); 73 | 74 | } 75 | 76 | @SuppressWarnings("unchecked") 77 | private Constructor findConstructor(Class proxyClass) { 78 | // currently each callback handler defines only one constructor, so shortcut the search 79 | return (Constructor) proxyClass.getDeclaredConstructors()[0]; 80 | } 81 | 82 | @SuppressWarnings("unchecked") 83 | private Class createProxyClass(ByteBuddy byteBuddy, Class interfaceType) { 84 | return (Class) byteBuddy 85 | .subclass(CallbackHandlerProxy.class) 86 | .implement(interfaceType) 87 | .method(isDeclaredBy(interfaceType)) 88 | .intercept(to(CallbackHandlerInterceptor.class)) 89 | .make() 90 | .load(interfaceType.getClassLoader()) 91 | .getLoaded(); 92 | } 93 | 94 | /** 95 | * Base proxy class. 96 | * 97 | * ByteBuddy subclass this and add corresponding interface. 98 | */ 99 | public static class CallbackHandlerProxy { 100 | private CallbackHandler callbackHandler; 101 | 102 | public CallbackHandlerProxy(CallbackHandler callbackHandler) { 103 | this.callbackHandler = callbackHandler; 104 | } 105 | 106 | public Object invoke(Method method, Object[] args) throws Throwable { 107 | return callbackHandler.invoke(this, method, args); 108 | } 109 | } 110 | 111 | /** 112 | * Interceptor for proxy of {@link CallbackHandlerProxy}. 113 | * 114 | * Simply delegates the invocation of proxy instance to the callback handler instance. 115 | */ 116 | public static class CallbackHandlerInterceptor { 117 | @RuntimeType 118 | public static Object intercept(@AllArguments Object[] args, @Origin Method method, @This CallbackHandlerProxy callbackHandler) throws Throwable { 119 | return callbackHandler.invoke(method, args); // delegate to callback handler logic 120 | } 121 | } 122 | 123 | @Override 124 | public ConnectionFactory wrapConnectionFactory(ConnectionFactory connectionFactory) { 125 | ConnectionFactoryCallbackHandler handler = new ConnectionFactoryCallbackHandler(connectionFactory, this.proxyConfig); 126 | return instantiate(this.connectionFactoryProxyConstructor, handler); 127 | } 128 | 129 | @Override 130 | public Connection wrapConnection(Connection connection, ConnectionInfo connectionInfo) { 131 | ConnectionCallbackHandler handler = new ConnectionCallbackHandler(connection, connectionInfo, this.proxyConfig); 132 | return instantiate(this.connectionProxyConstructor, handler); 133 | } 134 | 135 | @Override 136 | public Batch wrapBatch(Batch batch, ConnectionInfo connectionInfo) { 137 | BatchCallbackHandler handler = new BatchCallbackHandler(batch, connectionInfo, this.proxyConfig); 138 | return instantiate(this.batchProxyConstructor, handler); 139 | } 140 | 141 | @Override 142 | public Statement wrapStatement(Statement statement, StatementInfo statementInfo, ConnectionInfo connectionInfo) { 143 | StatementCallbackHandler handler = new StatementCallbackHandler(statement, statementInfo, connectionInfo, this.proxyConfig); 144 | return instantiate(this.statementProxyConstructor, handler); 145 | } 146 | 147 | @Override 148 | public Result wrapResult(Result result, QueryExecutionInfo queryExecutionInfo) { 149 | ResultCallbackHandler handler = new ResultCallbackHandler(result, queryExecutionInfo, this.proxyConfig); 150 | return instantiate(this.resultProxyConstructor, handler); 151 | } 152 | 153 | private T instantiate(Constructor constructor, Object... args) { 154 | try { 155 | return constructor.newInstance(args); 156 | } 157 | catch (Exception e) { 158 | throw new RuntimeException("Failed to create an instance", e); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /java-agent-example/common/src/main/java/io/r2dbc/examples/agent/R2dbcProxyAgent.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples.agent; 2 | 3 | import java.lang.instrument.Instrumentation; 4 | import java.lang.reflect.Method; 5 | import java.util.concurrent.Callable; 6 | 7 | import io.r2dbc.proxy.callback.ConnectionFactoryCallbackHandler; 8 | import io.r2dbc.proxy.callback.ProxyConfig; 9 | import io.r2dbc.proxy.core.MethodExecutionInfo; 10 | import io.r2dbc.proxy.core.QueryExecutionInfo; 11 | import io.r2dbc.proxy.listener.LifeCycleListener; 12 | import io.r2dbc.proxy.listener.ProxyExecutionListener; 13 | import io.r2dbc.proxy.support.MethodExecutionInfoFormatter; 14 | import io.r2dbc.proxy.support.QueryExecutionInfoFormatter; 15 | import io.r2dbc.spi.Connection; 16 | import io.r2dbc.spi.ConnectionFactory; 17 | import net.bytebuddy.agent.builder.AgentBuilder; 18 | import net.bytebuddy.implementation.bind.annotation.AllArguments; 19 | import net.bytebuddy.implementation.bind.annotation.Origin; 20 | import net.bytebuddy.implementation.bind.annotation.RuntimeType; 21 | import net.bytebuddy.implementation.bind.annotation.SuperCall; 22 | import net.bytebuddy.implementation.bind.annotation.This; 23 | import org.reactivestreams.Publisher; 24 | import reactor.core.publisher.Mono; 25 | 26 | import static java.lang.String.format; 27 | import static net.bytebuddy.implementation.MethodDelegation.to; 28 | import static net.bytebuddy.matcher.ElementMatchers.isSubTypeOf; 29 | import static net.bytebuddy.matcher.ElementMatchers.named; 30 | 31 | /** 32 | * Sample Java Agent. 33 | * 34 | * This agent instruments {@link ConnectionFactory} and make the target application 35 | * participate to the r2dbc-proxy framework. 36 | * 37 | * @author Tadaya Tsuyukubo 38 | */ 39 | public class R2dbcProxyAgent { 40 | 41 | private static ProxyConfig proxyConfig = createProxyConfig(); 42 | 43 | /** 44 | * Configure the given {@link ProxyConfig}. 45 | */ 46 | private static ProxyConfig createProxyConfig() { 47 | 48 | // as an example, printing out any method interactions and executed query. 49 | 50 | QueryExecutionInfoFormatter queryFormatter = QueryExecutionInfoFormatter.showAll(); 51 | MethodExecutionInfoFormatter formatter = MethodExecutionInfoFormatter.withDefault(); 52 | 53 | ProxyConfig.Builder builder = ProxyConfig.builder(); 54 | 55 | builder.listener(new ProxyExecutionListener() { 56 | @Override 57 | public void beforeMethod(MethodExecutionInfo executionInfo) { 58 | System.out.println("Before >> " + formatter.format(executionInfo)); 59 | } 60 | 61 | @Override 62 | public void afterMethod(MethodExecutionInfo executionInfo) { 63 | System.out.println("After >> " + formatter.format(executionInfo)); 64 | } 65 | 66 | @Override 67 | public void afterQuery(QueryExecutionInfo execInfo) { 68 | System.out.println(queryFormatter.format(execInfo)); 69 | } 70 | }); 71 | 72 | // To add LifeCycleListener, it needs to be wrapped by LifeCycleExecutionListener 73 | builder.listener(new LifeCycleListener() { 74 | @Override 75 | public void afterCreateOnConnectionFactory(MethodExecutionInfo methodExecutionInfo) { 76 | String msg = format(">> Connection acquired. took=%sms", methodExecutionInfo.getExecuteDuration().toMillis()); 77 | System.out.println(msg); 78 | } 79 | }); 80 | 81 | // Optional: use ByteBuddy to create proxies 82 | builder.proxyFactoryFactory(ByteBuddyProxyFactory::new); 83 | 84 | return builder.build(); 85 | } 86 | 87 | 88 | public static void premain(String arg, Instrumentation inst) { 89 | 90 | System.out.println("\n\n\n"); 91 | System.out.println("*****************************"); 92 | System.out.println(">>> Java Agent Activated <<<"); 93 | System.out.println("*****************************"); 94 | System.out.println("\n\n\n"); 95 | 96 | instrument(inst); 97 | } 98 | 99 | private static void instrument(Instrumentation inst) { 100 | // intercept methods defined on ConnectionFactory 101 | new AgentBuilder.Default() 102 | .type(isSubTypeOf(ConnectionFactory.class)) 103 | .transform((builder, typeDescription, classLoader, module) -> builder 104 | .method(named("create").or(named("getMetadata"))) 105 | .intercept(to(ConnectionFactoryInterceptor.class)) 106 | ) 107 | .installOn(inst); 108 | 109 | } 110 | 111 | /** 112 | * Interceptor implementation. 113 | * 114 | * Intercept {@link ConnectionFactory#create()} and{@link ConnectionFactory#getMetadata()} 115 | * methods. Then, perform proxy invocation logic. 116 | * The returned object is a proxy object and any interaction to it triggers callback 117 | * for listeners from r2dbc-proxy framework. 118 | * In other words, this is the entry point to the r2dbc-proxy framework. 119 | */ 120 | @SuppressWarnings("unchecked") 121 | public static class ConnectionFactoryInterceptor { 122 | 123 | @RuntimeType 124 | public static Object intercept(@AllArguments Object[] args, 125 | @This ConnectionFactory connectionFactory, @Origin Method method, 126 | @SuperCall Callable callable) throws Throwable { 127 | 128 | // Create callback handler for ConnectionFactory methods. 129 | // Also, update invocation strategy to directly returns the target object. 130 | 131 | // If invocation strategy is not set, default strategy performs a reflective 132 | // method call on the original ConnectionFactory instance. 133 | // However, for ByteBuddy, again the call get intercepted. So, it becomes 134 | // infinite loop of interceptions. 135 | 136 | ConnectionFactoryCallbackHandler handler = new ConnectionFactoryCallbackHandler(connectionFactory, proxyConfig); 137 | handler.setMethodInvocationStrategy((invokedMethod, invokedTarget, invokedArgs) -> { 138 | return callable.call(); // retrieve original result 139 | }); 140 | 141 | 142 | // currently proxy argument(first arg) is not used. just passing fake object. 143 | Object result = handler.invoke("", method, args); 144 | 145 | 146 | String methodName = method.getName(); 147 | 148 | if ("getMetadata".equals(methodName)) { 149 | return result; // result is ConnectionFactoryMetadata 150 | } 151 | 152 | // handling for "ConnectionFactory#create()" 153 | 154 | // "ConnectionFactory#create()" defines return type as "Publisher". 155 | // Usually driver implementation class declares it as Mono. 156 | // On the other hand, the callback handler returns the proxy always as Flux in order to 157 | // handle method call generically. 158 | // This is not a problem in regular case; however, since ByteBuddy requires exact 159 | // type to be returned for its subclass, here requires converting the result to Mono. 160 | // To be defensive, check the return type. If the return type is not Mono(must be Flux), 161 | // then return as is. 162 | if (Mono.class.equals(method.getReturnType())) { 163 | return Mono.from((Publisher) result); 164 | } 165 | return result; // return as Flux 166 | 167 | } 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /java-agent-example/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /java-agent-example/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /java-agent-example/package-agent/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | r2dbc-proxy-examples-agent-agent 6 | jar 7 | r2dbc-proxy-examples-agent-agent 8 | http://maven.apache.org 9 | 10 | 11 | net.ttddyy 12 | r2dbc-proxy-examples-agent-parent 13 | 1.0-SNAPSHOT 14 | ../pom.xml 15 | 16 | 17 | 18 | examples-agent-${pom.version} 19 | 20 | 21 | 22 | org.apache.maven.plugins 23 | maven-compiler-plugin 24 | ${compiler.version} 25 | 26 | ${java.version} 27 | ${java.version} 28 | ${java.version} 29 | ${java.version} 30 | 31 | 32 | 33 | 34 | org.apache.maven.plugins 35 | maven-dependency-plugin 36 | 37 | 38 | unpack 39 | prepare-package 40 | 41 | unpack 42 | 43 | 44 | 45 | 46 | net.ttddyy 47 | r2dbc-proxy-examples-agent-common 48 | 49 | ${project.version} 50 | jar 51 | **/agent/** 52 | ${project.build.outputDirectory} 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.apache.maven.plugins 63 | maven-assembly-plugin 64 | 65 | examples-agent-${pom.version} 66 | 67 | jar-with-dependencies 68 | 69 | 70 | true 71 | 72 | io.r2dbc.examples.agent.R2dbcProxyAgent 73 | 74 | 75 | 76 | 77 | 78 | 79 | assemble-all 80 | package 81 | 82 | single 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | net.ttddyy 97 | r2dbc-proxy-examples-agent-common 98 | ${project.version} 99 | provided 100 | 101 | 102 | 103 | 104 | io.r2dbc 105 | r2dbc-proxy 106 | 107 | 108 | org.slf4j 109 | slf4j-api 110 | 111 | 112 | 113 | 114 | 115 | net.bytebuddy 116 | byte-buddy 117 | ${byte-buddy.version} 118 | 119 | 120 | net.bytebuddy 121 | byte-buddy-agent 122 | ${byte-buddy.version} 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /java-agent-example/package-application/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | r2dbc-proxy-examples-agent-application 6 | jar 7 | r2dbc-proxy-examples-agent-application 8 | http://maven.apache.org 9 | 10 | 11 | net.ttddyy 12 | r2dbc-proxy-examples-agent-parent 13 | 1.0-SNAPSHOT 14 | ../pom.xml 15 | 16 | 17 | 18 | examples-application-${pom.version} 19 | 20 | 21 | 22 | org.apache.maven.plugins 23 | maven-compiler-plugin 24 | ${compiler.version} 25 | 26 | ${java.version} 27 | ${java.version} 28 | ${java.version} 29 | ${java.version} 30 | 31 | 32 | 33 | 34 | org.apache.maven.plugins 35 | maven-surefire-plugin 36 | ${surefire.version} 37 | 38 | random 39 | 40 | 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-dependency-plugin 45 | 46 | 47 | unpack 48 | prepare-package 49 | 50 | unpack 51 | 52 | 53 | 54 | 55 | net.ttddyy 56 | r2dbc-proxy-examples-agent-common 57 | ${project.version} 58 | jar 59 | **/Application.class 60 | ${project.build.outputDirectory} 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-maven-plugin 72 | ${spring-boot.version} 73 | 74 | 75 | 76 | repackage 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | net.ttddyy 90 | r2dbc-proxy-examples-agent-common 91 | ${project.version} 92 | 93 | 94 | 95 | org.springframework.boot 96 | spring-boot-starter-web 97 | 98 | 99 | org.springframework.boot 100 | spring-boot-starter-webflux 101 | 102 | 103 | org.springframework.boot 104 | spring-boot-starter-jdbc 105 | 106 | 107 | org.springframework.boot 108 | spring-boot-starter-actuator 109 | 110 | 111 | 112 | org.springframework.data 113 | spring-data-r2dbc 114 | 115 | 116 | 117 | io.r2dbc 118 | r2dbc-h2 119 | 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /java-agent-example/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | net.ttddyy 6 | r2dbc-proxy-examples-agent-parent 7 | pom 8 | 1.0-SNAPSHOT 9 | r2dbc-proxy-examples-agent-parent 10 | http://maven.apache.org 11 | 12 | 13 | 14 | common 15 | package-agent 16 | package-application 17 | 18 | 19 | 20 | UTF-8 21 | 22 | 1.8 23 | 24 | 25 | 3.8.0 26 | 2.22.1 27 | 3.0.1 28 | 3.0.1 29 | 2.5.3 30 | 31 | 32 | 2.3.2.RELEASE 33 | 1.9.16 34 | 35 | 36 | 37 | 38 | 39 | spring-snapshots 40 | Spring Snapshots 41 | https://repo.spring.io/snapshot 42 | 43 | true 44 | 45 | 46 | 47 | spring-milestones 48 | Spring Milestones 49 | https://repo.spring.io/milestone 50 | 51 | false 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-dependencies 61 | ${spring-boot.version} 62 | pom 63 | import 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /listener-example/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.net.*; 21 | import java.io.*; 22 | import java.nio.channels.*; 23 | import java.util.Properties; 24 | 25 | public class MavenWrapperDownloader { 26 | 27 | /** 28 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 29 | */ 30 | private static final String DEFAULT_DOWNLOAD_URL = 31 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 32 | 33 | /** 34 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 35 | * use instead of the default one. 36 | */ 37 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 38 | ".mvn/wrapper/maven-wrapper.properties"; 39 | 40 | /** 41 | * Path where the maven-wrapper.jar will be saved to. 42 | */ 43 | private static final String MAVEN_WRAPPER_JAR_PATH = 44 | ".mvn/wrapper/maven-wrapper.jar"; 45 | 46 | /** 47 | * Name of the property which should be used to override the default download url for the wrapper. 48 | */ 49 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 50 | 51 | public static void main(String args[]) { 52 | System.out.println("- Downloader started"); 53 | File baseDirectory = new File(args[0]); 54 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 55 | 56 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 57 | // wrapperUrl parameter. 58 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 59 | String url = DEFAULT_DOWNLOAD_URL; 60 | if(mavenWrapperPropertyFile.exists()) { 61 | FileInputStream mavenWrapperPropertyFileInputStream = null; 62 | try { 63 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 64 | Properties mavenWrapperProperties = new Properties(); 65 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 66 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 67 | } catch (IOException e) { 68 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 69 | } finally { 70 | try { 71 | if(mavenWrapperPropertyFileInputStream != null) { 72 | mavenWrapperPropertyFileInputStream.close(); 73 | } 74 | } catch (IOException e) { 75 | // Ignore ... 76 | } 77 | } 78 | } 79 | System.out.println("- Downloading from: : " + url); 80 | 81 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 82 | if(!outputFile.getParentFile().exists()) { 83 | if(!outputFile.getParentFile().mkdirs()) { 84 | System.out.println( 85 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 86 | } 87 | } 88 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 89 | try { 90 | downloadFileFromURL(url, outputFile); 91 | System.out.println("Done"); 92 | System.exit(0); 93 | } catch (Throwable e) { 94 | System.out.println("- Error downloading"); 95 | e.printStackTrace(); 96 | System.exit(1); 97 | } 98 | } 99 | 100 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 101 | URL website = new URL(urlString); 102 | ReadableByteChannel rbc; 103 | rbc = Channels.newChannel(website.openStream()); 104 | FileOutputStream fos = new FileOutputStream(destination); 105 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 106 | fos.close(); 107 | rbc.close(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /listener-example/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /listener-example/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /listener-example/README.md: -------------------------------------------------------------------------------- 1 | # listener-example 2 | 3 | [r2dbc-proxy][r2dbc-proxy] sample projects. 4 | 5 | ## Samples 6 | 7 | - Tracing with Sleuth 8 | - Metrics with Micrometer (and log slow query) 9 | - Use different mechanism to create proxy 10 | - `SpringAopProxyFactory` uses spring's `ProxyFactory` to create proxy instances. 11 | 12 | ## Tracing with Sleuth 13 | 14 | **[TracingExecutionListener](./src/main/java/io/r2dbc/examples/TracingExecutionListener.java)** : 15 | _Instrument R2DBC interaction to create tracing spans_. 16 | 17 | 18 | ### Sample tracing images 19 | 20 | Tracing query 21 | 22 | ![Tracing query](images/zipkin-tracing-query.png) 23 | 24 | Tracing transaction 25 | 26 | ![Tracing transaction](images/zipkin-tracing-transaction.png) 27 | 28 | Tracing transaction rollback 29 | 30 | ![Tracing transaction rollback](images/zipkin-tracing-rollback.png) 31 | 32 | Connection Span 33 | 34 | ![Connection span](images/zipkin-span-connection.png) 35 | 36 | Transaction Span 37 | 38 | ![Transaction span](images/zipkin-span-transaction.png) 39 | 40 | Quey Span (Single Query) 41 | 42 | ![Query span](images/zipkin-span-query.png) 43 | 44 | Quey Span (Batch Query) 45 | 46 | ![Query batch span](images/zipkin-span-batch-query.png) 47 | 48 | 49 | ## Metrics with Micrometer (and log slow query) 50 | 51 | **[MetricsExecutionListener](./src/main/java/io/r2dbc/examples/MetricsExecutionListener.java)** : 52 | _Populates following metrics:_ 53 | 54 | - Time took to create a connection 55 | - Commit and rollback counts 56 | - Executed query count 57 | - Slow query count 58 | 59 | Metrics are accessible via JMX and metrics endpoint(`/actuator/metrics`). 60 | 61 | Also, logs slow queries that took more than 500ms. 62 | 63 | 64 | ## Sample metrics images 65 | 66 | *JMX entries:* 67 | 68 | ![JMX entries](images/metrics-jmx-entries.png) 69 | 70 | *Connection metrics on JMX:* 71 | 72 | ![JMX Connection](images/metrics-jmx-connection.png) 73 | 74 | *Query metrics on JMX:* 75 | 76 | ![JMX Query](images/metrics-jmx-query.png) 77 | 78 | *Connection metrics on actuator (`/actuator/metrics/r2dbc.connection`):* 79 | 80 | ![Actuator Connection](images/metrics-actuator-connection.png) 81 | 82 | *Transaction metrics on actuator (`/actuator/metrics/r2dbc.transaction`):* 83 | 84 | ![Actuator Transaction](images/metrics-actuator-transaction.png) 85 | 86 | *Slow query log:* 87 | ![Slow query log](images/metrics-slow-query-log.png) 88 | 89 | ---- 90 | 91 | # How to run 92 | 93 | Start zipkin 94 | ```shell 95 | > docker run -d -p 9411:9411 openzipkin/zipkin 96 | ``` 97 | 98 | Start `Application` 99 | 100 | Access endpoints 101 | ```shell 102 | > curl localhost:8080 103 | > curl localhost:8080/transaction 104 | > curl localhost:8080/rollback 105 | > curl localhost:8080/slow 106 | ``` 107 | 108 | - `R2dbcSpiController` for endpoints(`/spi/*`) with access using R2DBC SPIs 109 | - `DatabaseClientController` for endpoints(`/spring/*`) with access using `DatabseClient` from Spring 110 | 111 | Metrics actuator endpoint 112 | 113 | ```shell 114 | > curl localhost:8080/actuator/metrics 115 | ``` 116 | 117 | ---- 118 | 119 | [r2dbc-proxy]: https://github.com/r2dbc/r2dbc-proxy 120 | [LifeCycleListener]: https://github.com/r2dbc/r2dbc-proxy/blob/master/src/main/java/io/r2dbc/proxy/listener/LifeCycleListener.java 121 | -------------------------------------------------------------------------------- /listener-example/images/metrics-actuator-connection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/metrics-actuator-connection.png -------------------------------------------------------------------------------- /listener-example/images/metrics-actuator-transaction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/metrics-actuator-transaction.png -------------------------------------------------------------------------------- /listener-example/images/metrics-jmx-connection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/metrics-jmx-connection.png -------------------------------------------------------------------------------- /listener-example/images/metrics-jmx-entries.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/metrics-jmx-entries.png -------------------------------------------------------------------------------- /listener-example/images/metrics-jmx-query.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/metrics-jmx-query.png -------------------------------------------------------------------------------- /listener-example/images/metrics-slow-query-log.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/metrics-slow-query-log.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-span-batch-query.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-span-batch-query.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-span-connection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-span-connection.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-span-query.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-span-query.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-span-transaction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-span-transaction.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-tracing-query.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-tracing-query.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-tracing-rollback.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-tracing-rollback.png -------------------------------------------------------------------------------- /listener-example/images/zipkin-tracing-transaction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ttddyy/r2dbc-proxy-examples/41f5a8d0235882b31a37a19e935d4ac14c6ccd03/listener-example/images/zipkin-tracing-transaction.png -------------------------------------------------------------------------------- /listener-example/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /listener-example/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /listener-example/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | net.ttddyy 6 | r2dbc-proxy-examples-listener 7 | jar 8 | 1.0-SNAPSHOT 9 | r2dbc-proxy-examples-listener 10 | http://maven.apache.org 11 | 12 | 13 | 14 | UTF-8 15 | 16 | 1.8 17 | 18 | 19 | 3.8.0 20 | 2.22.1 21 | 3.0.1 22 | 3.0.1 23 | 2.5.3 24 | 25 | 26 | 2.2.5.RELEASE 27 | Arabba-SR9 28 | 29 | 30 | 31 | 32 | 33 | spring-snapshots 34 | Spring Snapshots 35 | https://repo.spring.io/snapshot 36 | 37 | true 38 | 39 | 40 | 41 | spring-milestones 42 | Spring Milestones 43 | https://repo.spring.io/milestone 44 | 45 | false 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.apache.maven.plugins 55 | maven-compiler-plugin 56 | ${compiler.version} 57 | 58 | ${java.version} 59 | ${java.version} 60 | ${java.version} 61 | ${java.version} 62 | 63 | 64 | 65 | 66 | org.apache.maven.plugins 67 | maven-surefire-plugin 68 | ${surefire.version} 69 | 70 | random 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | io.r2dbc 82 | r2dbc-bom 83 | ${r2dbc-bom.version} 84 | pom 85 | import 86 | 87 | 88 | 89 | org.springframework.cloud 90 | spring-cloud-sleuth 91 | ${spring-cloud-sleuth.version} 92 | pom 93 | import 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | org.springframework.cloud 103 | spring-cloud-starter-zipkin 104 | 105 | 106 | 107 | io.micrometer 108 | micrometer-registry-jmx 109 | 110 | 111 | 112 | org.springframework.boot 113 | spring-boot-starter-web 114 | 115 | 116 | org.springframework.boot 117 | spring-boot-starter-webflux 118 | 119 | 120 | org.springframework.boot 121 | spring-boot-starter-jdbc 122 | 123 | 124 | org.springframework.boot 125 | spring-boot-starter-actuator 126 | 127 | 128 | 129 | org.springframework.data 130 | spring-data-r2dbc 131 | 132 | 133 | 134 | io.r2dbc 135 | r2dbc-h2 136 | 137 | 138 | io.r2dbc 139 | r2dbc-proxy 140 | 141 | 142 | 143 | org.springframework.boot 144 | spring-boot-starter-test 145 | test 146 | 147 | 148 | org.junit.vintage 149 | junit-vintage-engine 150 | 151 | 152 | 153 | 154 | 155 | io.zipkin.brave 156 | brave-tests 157 | 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/Application.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import brave.Tracer; 4 | import io.micrometer.core.annotation.Timed; 5 | import io.micrometer.core.instrument.MeterRegistry; 6 | import io.r2dbc.h2.H2ConnectionConfiguration; 7 | import io.r2dbc.h2.H2ConnectionFactory; 8 | import io.r2dbc.proxy.ProxyConnectionFactory; 9 | import io.r2dbc.proxy.callback.ProxyConfig; 10 | import io.r2dbc.proxy.support.QueryExecutionInfoFormatter; 11 | import io.r2dbc.spi.ConnectionFactory; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.CommandLineRunner; 14 | import org.springframework.boot.SpringApplication; 15 | import org.springframework.boot.autoconfigure.SpringBootApplication; 16 | import org.springframework.context.annotation.Bean; 17 | import org.springframework.data.r2dbc.core.DatabaseClient; 18 | import org.springframework.jdbc.core.JdbcOperations; 19 | import org.springframework.jdbc.core.JdbcTemplate; 20 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 21 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 22 | import org.springframework.transaction.reactive.TransactionalOperator; 23 | import org.springframework.web.bind.annotation.RequestMapping; 24 | import org.springframework.web.bind.annotation.RestController; 25 | import reactor.core.publisher.Flux; 26 | import reactor.core.publisher.Mono; 27 | 28 | import javax.sql.DataSource; 29 | import java.time.Duration; 30 | 31 | /** 32 | * R2DBC proxy sample application 33 | */ 34 | @SpringBootApplication 35 | @RestController 36 | @Timed 37 | public class Application { 38 | 39 | public static void main(String[] args) { 40 | SpringApplication.run(Application.class, args); 41 | } 42 | 43 | @Autowired 44 | DatabaseClient databaseClient; 45 | 46 | @Autowired 47 | TransactionalOperator operator; 48 | 49 | @RequestMapping("/") 50 | Flux select() { 51 | return this.databaseClient.execute("SELECT value FROM test;") 52 | .map(row -> row.get("value", Integer.class)) 53 | .all(); 54 | } 55 | 56 | // 57 | @RequestMapping("/transaction") 58 | Mono transaction() { 59 | return this.databaseClient.execute("INSERT INTO test VALUES (:value)") 60 | .bind("value", 200) 61 | .fetch().rowsUpdated().as(this.operator::transactional); 62 | } 63 | 64 | // TODO: find a way to manually rollback transaction 65 | // @RequestMapping("/rollback") 66 | // Mono rollback() { 67 | // return this.databaseClient.execute("INSERT INTO test VALUES (:value)") 68 | // .bind("value", "ABC") // wrong value type 69 | // .fetch().rowsUpdated().as(this.operator::transactional) 70 | // .onErrorResume(t -> Mono.just(-99)); 71 | // } 72 | 73 | @RequestMapping("/slow") 74 | Flux slow() { 75 | return this.databaseClient.execute("CALL SLEEP(700);").map(row -> Mono.just(-1)).all(); 76 | } 77 | 78 | @Bean 79 | DataSource dataSource() { 80 | return new EmbeddedDatabaseBuilder() 81 | .setType(EmbeddedDatabaseType.H2) 82 | .build(); 83 | } 84 | 85 | @Bean 86 | CommandLineRunner bootstrap(DataSource dataSource) { 87 | return args -> { 88 | JdbcOperations jdbcOperations = new JdbcTemplate(dataSource); 89 | jdbcOperations.execute("DROP TABLE IF EXISTS test"); 90 | jdbcOperations.execute("CREATE TABLE test ( value INTEGER )"); 91 | jdbcOperations.execute("INSERT INTO test VALUES (100)"); 92 | jdbcOperations.execute("INSERT INTO test VALUES (200)"); 93 | jdbcOperations.execute("INSERT INTO test VALUES (99)"); 94 | 95 | // create sleep function for slow query 96 | jdbcOperations.execute("CREATE ALIAS SLEEP FOR \"java.lang.Thread.sleep(long)\""); 97 | }; 98 | } 99 | 100 | @Bean 101 | ConnectionFactory connectionFactory(Tracer tracer, MeterRegistry meterRegistry) { 102 | H2ConnectionConfiguration h2Configuration = H2ConnectionConfiguration.builder() 103 | .username("sa") 104 | .password("") 105 | .inMemory("testdb") 106 | .build(); 107 | 108 | 109 | ConnectionFactory connectionFactory = new H2ConnectionFactory(h2Configuration); 110 | 111 | TracingExecutionListener tracingListener = new TracingExecutionListener(tracer); 112 | MetricsExecutionListener metricsListener = new MetricsExecutionListener(meterRegistry, Duration.ofMillis(500)); 113 | QueryTimeMetricsExecutionListener queryTimeListener = new QueryTimeMetricsExecutionListener(meterRegistry); 114 | 115 | QueryExecutionInfoFormatter queryFormatter = QueryExecutionInfoFormatter.showAll(); 116 | 117 | // Example to use different proxy creation mechanism. 118 | ProxyConfig proxyConfig = new ProxyConfig(); 119 | proxyConfig.setProxyFactoryFactory(SpringAopProxyFactory::new); 120 | 121 | ConnectionFactory proxyConnectionFactory = 122 | ProxyConnectionFactory.builder(connectionFactory, proxyConfig) 123 | .listener(tracingListener) 124 | .listener(metricsListener) 125 | .listener(queryTimeListener) 126 | .onAfterQuery(queryInfo -> { 127 | System.out.println(queryFormatter.format(queryInfo)); 128 | }) 129 | .build(); 130 | 131 | return proxyConnectionFactory; 132 | } 133 | 134 | @Bean 135 | DatabaseClient databaseClient(ConnectionFactory connectionFactory) { 136 | return DatabaseClient.create(connectionFactory); 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/DatabaseClientController.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import org.springframework.data.r2dbc.core.DatabaseClient; 4 | import org.springframework.transaction.reactive.TransactionalOperator; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | import reactor.core.publisher.Flux; 9 | import reactor.core.publisher.Mono; 10 | 11 | /** 12 | * Provides endpoints using {@link DatabaseClient}. 13 | * 14 | * @author Tadaya Tsuyukubo 15 | */ 16 | @RestController 17 | @RequestMapping(path = "/spring") 18 | public class DatabaseClientController { 19 | 20 | private final DatabaseClient databaseClient; 21 | private final TransactionalOperator operator; 22 | 23 | public DatabaseClientController(DatabaseClient databaseClient, TransactionalOperator operator) { 24 | this.databaseClient = databaseClient; 25 | this.operator = operator; 26 | } 27 | 28 | @GetMapping 29 | String hi() { 30 | return "Hi from " + getClass().getSimpleName(); 31 | } 32 | 33 | // Perform a query without transaction 34 | @GetMapping("/simple") 35 | Flux simple() { 36 | return this.databaseClient.execute("SELECT value FROM test;") 37 | .map(row -> row.get("value", Integer.class)) 38 | .all(); 39 | } 40 | 41 | @GetMapping("/first") 42 | Mono first() { 43 | return this.databaseClient.execute("SELECT value FROM test;") 44 | .map(row -> row.get("value", Integer.class)) 45 | .first(); 46 | } 47 | 48 | @GetMapping("/one") 49 | Mono one() { 50 | return this.databaseClient.execute("SELECT value FROM test WHERE value=99;") 51 | .map(row -> row.get("value", Integer.class)) 52 | .one(); 53 | } 54 | 55 | 56 | // Perform an update query with transaction 57 | @GetMapping("/tx") 58 | Mono tx() { 59 | return this.databaseClient.execute("INSERT INTO test VALUES (:value)") 60 | .bind("value", 100) 61 | .fetch().rowsUpdated().as(this.operator::transactional); 62 | } 63 | 64 | // Single transaction with multiple queries 65 | @RequestMapping("/tx-with-queries") 66 | Flux txWithQueries() { 67 | Mono execute1 = this.databaseClient.execute("INSERT INTO test VALUES (:value)") 68 | .bind("value", 100) 69 | .fetch().rowsUpdated(); 70 | Mono execute2 = this.databaseClient.execute("INSERT INTO test VALUES (:value)") 71 | .bind("value", 200) 72 | .fetch().rowsUpdated(); 73 | return Flux.concat(execute1, execute2).as(this.operator::transactional); 74 | } 75 | 76 | 77 | // Multiple Tx on single connection 78 | // @GetMapping("/multi-tx") 79 | // Flux multipleTx() { 80 | // Mono execute1 = this.databaseClient.execute("INSERT INTO test VALUES (:value)") 81 | // .bind("value", 100) 82 | // .fetch().rowsUpdated(); 83 | // Mono execute2 = this.databaseClient.execute("INSERT INTO test VALUES (:value)") 84 | // .bind("value", 200) 85 | // .fetch().rowsUpdated(); 86 | // 87 | // Mono action1 = execute1.as(this.operator::transactional); 88 | // Mono action2 = execute2.as(this.operator::transactional); 89 | // return Flux.concat(action1, action2); 90 | // } 91 | 92 | // Explicit rollback 93 | @GetMapping("/rollback") 94 | Flux rollback() { 95 | Mono execute = this.databaseClient.execute("INSERT INTO test VALUES (:value)") 96 | .bind("value", 100) 97 | .fetch().rowsUpdated(); 98 | return this.operator.execute(status -> { 99 | status.setRollbackOnly(); 100 | return execute; 101 | }).ofType(Integer.class); 102 | } 103 | 104 | // Batch 105 | 106 | // Error 107 | @GetMapping("/error") 108 | Flux error() { 109 | return this.databaseClient.execute("SELECT SOMETHING_WRONG();").map(row -> row.get(0)).all(); 110 | } 111 | 112 | // Error with recovery 113 | @GetMapping("/error-recovery") 114 | Flux errorRecovery() { 115 | return this.databaseClient.execute("SELECT SOMETHING_WRONG();") 116 | .map(row -> row.get(0)) 117 | .all() 118 | .onErrorReturn("recovered"); 119 | } 120 | 121 | // Error with transaction 122 | @GetMapping("/error-tx") 123 | Flux errorTx() { 124 | return this.databaseClient.execute("SELECT SOMETHING_WRONG();") 125 | .map(row -> row.get(0)) 126 | .all() 127 | .as(this.operator::transactional); 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/MetricsExecutionListener.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.micrometer.core.instrument.Counter; 4 | import io.micrometer.core.instrument.MeterRegistry; 5 | import io.micrometer.core.instrument.Timer; 6 | import io.r2dbc.proxy.core.MethodExecutionInfo; 7 | import io.r2dbc.proxy.core.QueryExecutionInfo; 8 | import io.r2dbc.proxy.listener.ProxyMethodExecutionListener; 9 | import io.r2dbc.proxy.support.QueryExecutionInfoFormatter; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import java.time.Duration; 14 | 15 | /** 16 | * Listener to populate micrometer metrics and logs slow query. 17 | * 18 | * @author Tadaya Tsuyukubo 19 | */ 20 | public class MetricsExecutionListener implements ProxyMethodExecutionListener { 21 | private static final Logger logger = LoggerFactory.getLogger(MetricsExecutionListener.class); 22 | 23 | private MeterRegistry registry; 24 | 25 | private String metricNamePrefix = "r2dbc."; 26 | 27 | private Duration slowQueryThreshold = Duration.ofSeconds(-1); // negative won't match any query 28 | 29 | private QueryExecutionInfoFormatter queryFormatter = new QueryExecutionInfoFormatter() 30 | .showTime() 31 | .showConnection() 32 | .showQuery(); 33 | 34 | public MetricsExecutionListener(MeterRegistry registry) { 35 | this.registry = registry; 36 | } 37 | 38 | public MetricsExecutionListener(MeterRegistry registry, Duration slowQueryThreshold) { 39 | this.registry = registry; 40 | this.slowQueryThreshold = slowQueryThreshold; 41 | } 42 | 43 | @Override 44 | public void beforeCreateOnConnectionFactory(MethodExecutionInfo methodExecutionInfo) { 45 | Timer.Sample sample = Timer.start(this.registry); 46 | methodExecutionInfo.getValueStore().put("connectionCreate", sample); 47 | } 48 | 49 | @Override 50 | public void afterCreateOnConnectionFactory(MethodExecutionInfo methodExecutionInfo) { 51 | Timer.Sample sample = methodExecutionInfo.getValueStore().get("connectionCreate", Timer.Sample.class); 52 | 53 | Timer timer = Timer 54 | .builder(this.metricNamePrefix + "connection") 55 | .description("Time to create(acquire) a connection") 56 | .tags("event", "create") 57 | .register(this.registry); 58 | 59 | sample.stop(timer); 60 | } 61 | 62 | @Override 63 | public void afterCommitTransactionOnConnection(MethodExecutionInfo methodExecutionInfo) { 64 | Counter counter = Counter 65 | .builder(this.metricNamePrefix + "transaction") 66 | .description("Num of transactions") 67 | .tags("event", "commit") 68 | .register(registry); 69 | counter.increment(); 70 | } 71 | 72 | @Override 73 | public void afterRollbackTransactionOnConnection(MethodExecutionInfo methodExecutionInfo) { 74 | incrementRollbackCounter(); 75 | } 76 | 77 | @Override 78 | public void afterRollbackTransactionToSavepointOnConnection(MethodExecutionInfo methodExecutionInfo) { 79 | incrementRollbackCounter(); 80 | } 81 | 82 | private void incrementRollbackCounter() { 83 | Counter counter = Counter 84 | .builder(this.metricNamePrefix + "transaction") 85 | .description("Num of transactions") 86 | .tags("event", "rollback") 87 | .register(registry); 88 | counter.increment(); 89 | } 90 | 91 | 92 | @Override 93 | public void afterExecuteOnBatch(QueryExecutionInfo queryExecutionInfo) { 94 | afterExecuteQuery(queryExecutionInfo); 95 | } 96 | 97 | @Override 98 | public void afterExecuteOnStatement(QueryExecutionInfo queryExecutionInfo) { 99 | afterExecuteQuery(queryExecutionInfo); 100 | } 101 | 102 | private void afterExecuteQuery(QueryExecutionInfo queryExecutionInfo) { 103 | Counter success = Counter 104 | .builder(this.metricNamePrefix + "query") 105 | .description("Num of executed queries") 106 | .register(this.registry); 107 | success.increment(); 108 | 109 | 110 | // when negative value is specified, do not log slow query 111 | if (this.slowQueryThreshold.isNegative()) { 112 | return; 113 | } 114 | 115 | if (this.slowQueryThreshold.minus(queryExecutionInfo.getExecuteDuration()).isNegative()) { 116 | Counter slowQueryCounter = Counter 117 | .builder(this.metricNamePrefix + "query.slow") 118 | .description("Slow query count that took more than threshold") 119 | .register(registry); 120 | slowQueryCounter.increment(); 121 | 122 | 123 | StringBuilder sb = new StringBuilder(); 124 | sb.append("SlowQuery: "); 125 | sb.append(this.queryFormatter.format(queryExecutionInfo)); 126 | logger.info(sb.toString()); 127 | } 128 | } 129 | 130 | public void setRegistry(MeterRegistry registry) { 131 | this.registry = registry; 132 | } 133 | 134 | public void setMetricNamePrefix(String metricNamePrefix) { 135 | this.metricNamePrefix = metricNamePrefix; 136 | } 137 | 138 | public void setSlowQueryThreshold(Duration slowQueryThreshold) { 139 | this.slowQueryThreshold = slowQueryThreshold; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/QueryTimeMetricsExecutionListener.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.micrometer.core.instrument.MeterRegistry; 4 | import io.micrometer.core.instrument.Timer; 5 | import io.r2dbc.proxy.core.QueryExecutionInfo; 6 | import io.r2dbc.proxy.core.QueryInfo; 7 | import io.r2dbc.proxy.listener.ProxyExecutionListener; 8 | 9 | import static java.lang.String.format; 10 | 11 | /** 12 | * Listener to populate micrometer metrics for query execution. 13 | *

14 | * Create time metrics for query execution by type(read/write). 15 | * https://github.com/micrometer-metrics/micrometer/issues/635 16 | * 17 | * @author Tadaya Tsuyukubo 18 | */ 19 | public class QueryTimeMetricsExecutionListener implements ProxyExecutionListener { 20 | 21 | private MeterRegistry registry; 22 | 23 | private String metricNamePrefix = "r2dbc."; 24 | 25 | private QueryTypeDetector queryTypeDetector = new DefaultQueryTypeDetector(); 26 | 27 | public QueryTimeMetricsExecutionListener(MeterRegistry registry) { 28 | this.registry = registry; 29 | } 30 | 31 | @Override 32 | public void afterQuery(QueryExecutionInfo queryExecutionInfo) { 33 | for (QueryInfo queryInfo : queryExecutionInfo.getQueries()) { 34 | String queryType = this.queryTypeDetector.detect(queryInfo.getQuery()).name().toLowerCase(); 35 | String metricsName = this.metricNamePrefix + "query." + queryType; 36 | String description = format("Time to execute %s queries", queryType); 37 | 38 | Timer timer = Timer 39 | .builder(metricsName) 40 | .description(description) 41 | .tags("event", "query") 42 | .register(this.registry); 43 | timer.record(queryExecutionInfo.getExecuteDuration()); 44 | } 45 | } 46 | 47 | 48 | public void setRegistry(MeterRegistry registry) { 49 | this.registry = registry; 50 | } 51 | 52 | public void setMetricNamePrefix(String metricNamePrefix) { 53 | this.metricNamePrefix = metricNamePrefix; 54 | } 55 | 56 | public void setQueryTypeDetector(QueryTypeDetector queryTypeDetector) { 57 | this.queryTypeDetector = queryTypeDetector; 58 | } 59 | 60 | public enum QueryType { 61 | SELECT, INSERT, UPDATE, DELETE, OTHER 62 | } 63 | 64 | public interface QueryTypeDetector { 65 | QueryType detect(String query); 66 | } 67 | 68 | public static class DefaultQueryTypeDetector implements QueryTypeDetector { 69 | @Override 70 | public QueryType detect(String query) { 71 | final String trimmedQuery = removeCommentAndWhiteSpace(query); 72 | if (trimmedQuery == null || trimmedQuery.length() < 6) { 73 | return QueryType.OTHER; 74 | } 75 | 76 | String prefix = trimmedQuery.substring(0, 6).toUpperCase(); 77 | final QueryType type; 78 | switch (prefix) { 79 | case "SELECT": 80 | type = QueryType.SELECT; 81 | break; 82 | case "INSERT": 83 | type = QueryType.INSERT; 84 | break; 85 | case "UPDATE": 86 | type = QueryType.UPDATE; 87 | break; 88 | case "DELETE": 89 | type = QueryType.DELETE; 90 | break; 91 | default: 92 | type = QueryType.OTHER; 93 | } 94 | return type; 95 | } 96 | 97 | private String removeCommentAndWhiteSpace(String query) { 98 | if (query == null) { 99 | return null; 100 | } 101 | return query.replaceAll("--.*\n", "").replaceAll("\n", "").replaceAll("/\\*.*\\*/", "").trim(); 102 | } 103 | 104 | } 105 | 106 | 107 | } 108 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/R2dbcSpiController.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.r2dbc.spi.Connection; 4 | import io.r2dbc.spi.ConnectionFactory; 5 | import io.r2dbc.spi.Result; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | import reactor.core.publisher.Flux; 10 | import reactor.core.publisher.Mono; 11 | 12 | import java.util.function.Function; 13 | import java.util.stream.Collectors; 14 | 15 | /** 16 | * Provide endpoints using R2DBC SPIs. 17 | * 18 | * @author Tadaya Tsuyukubo 19 | */ 20 | @RestController 21 | @RequestMapping(path = "/spi") 22 | public class R2dbcSpiController { 23 | 24 | private final ConnectionFactory connectionFactory; 25 | 26 | public R2dbcSpiController(ConnectionFactory connectionFactory) { 27 | this.connectionFactory = connectionFactory; 28 | } 29 | 30 | @GetMapping 31 | String hi() { 32 | return "Hi from " + getClass().getSimpleName(); 33 | } 34 | 35 | // Perform a query without transaction 36 | @GetMapping("/simple") 37 | Flux simple() { 38 | return Flux.usingWhen(this.connectionFactory.create(), connection -> { 39 | String query = "SELECT value FROM test"; 40 | Flux execute = Flux.from(connection.createStatement(query).execute()); 41 | Function> mapper = (result) -> Flux.from(result.map((row, rowMetadata) -> row.get("value", Integer.class))); 42 | return execute.flatMap(mapper); 43 | }, Connection::close, (c, err) -> c.close(), Connection::close); 44 | } 45 | 46 | @GetMapping("/multi-queries") 47 | Flux multiQueries() { 48 | return Flux.usingWhen(this.connectionFactory.create(), connection -> { 49 | String queries = "SELECT value FROM test; SELECT value FROM test"; 50 | Flux execute = Flux.from(connection.createStatement(queries).execute()); 51 | Function> mapper = (result) -> Flux.from(result.map((row, rowMetadata) -> row.get("value", Integer.class))); 52 | return execute.flatMap(mapper); 53 | }, Connection::close, (c, err) -> c.close(), Connection::close); 54 | } 55 | 56 | // Perform an update query with transaction 57 | @GetMapping("/tx") 58 | Mono tx() { 59 | return Mono.usingWhen(this.connectionFactory.create(), connection -> { 60 | String query = "INSERT INTO test VALUES ($1)"; 61 | Flux execute = Flux.from(connection.createStatement(query).bind("$1", "100").execute()); 62 | Function> mapper = (result) -> Mono.from(result.getRowsUpdated()); 63 | Flux action = execute.flatMap(mapper); 64 | 65 | return Flux.concat( 66 | Mono.from(connection.beginTransaction()).then(Mono.empty()), 67 | action, 68 | Mono.from(connection.commitTransaction()).then(Mono.empty()) 69 | ).collect(Collectors.summingInt(i -> i)); 70 | }, Connection::close, (c, err) -> c.close(), Connection::close); 71 | } 72 | 73 | @GetMapping("/tx-with-queries") 74 | Mono txWithQueries() { 75 | return Mono.usingWhen(this.connectionFactory.create(), connection -> { 76 | String query = "INSERT INTO test VALUES ($1)"; 77 | Function> mapper = (result) -> Mono.from(result.getRowsUpdated()); 78 | Flux execute1 = Flux.from(connection.createStatement(query).bind("$1", "100").execute()).flatMap(mapper); 79 | Flux execute2 = Flux.from(connection.createStatement(query).bind("$1", "200").execute()).flatMap(mapper); 80 | 81 | // add up num of updated rows 82 | Mono action = Flux.concat(execute1, execute2).collect(Collectors.summingInt(value -> value)); 83 | 84 | return Flux.concat( 85 | Mono.from(connection.beginTransaction()).then(Mono.empty()), 86 | action, 87 | Mono.from(connection.commitTransaction()).then(Mono.empty()) 88 | ).collect(Collectors.summingInt(i -> i)); 89 | }, Connection::close, (c, err) -> c.close(), Connection::close); 90 | } 91 | 92 | 93 | // Multiple Tx on single connection 94 | @GetMapping("/multi-tx") 95 | Flux multipleTx() { 96 | return Flux.usingWhen(this.connectionFactory.create(), connection -> { 97 | String query = "INSERT INTO test VALUES ($1)"; 98 | Function> mapper = (result) -> Mono.from(result.getRowsUpdated()); 99 | Flux execute1 = Flux.from(connection.createStatement(query).bind("$1", "100").execute()).flatMap(mapper); 100 | Flux execute2 = Flux.from(connection.createStatement(query).bind("$1", "200").execute()).flatMap(mapper); 101 | 102 | return Flux.concat( 103 | Mono.from(connection.beginTransaction()).then(Mono.empty()), 104 | execute1, 105 | Mono.from(connection.commitTransaction()).then(Mono.empty()), 106 | Mono.from(connection.beginTransaction()).then(Mono.empty()), 107 | execute2, 108 | Mono.from(connection.commitTransaction()).then(Mono.empty()) 109 | ); 110 | }, Connection::close, (c, err) -> c.close(), Connection::close); 111 | } 112 | 113 | // Explicit rollback 114 | @GetMapping("/rollback") 115 | Mono rollback() { 116 | return Mono.usingWhen(this.connectionFactory.create(), connection -> { 117 | String query = "INSERT INTO test VALUES ($1)"; 118 | Function> mapper = (result) -> Mono.from(result.getRowsUpdated()); 119 | Flux execute = Flux.from(connection.createStatement(query).bind("$1", "100").execute()).flatMap(mapper); 120 | 121 | return Flux.concat( 122 | Mono.from(connection.beginTransaction()).then(Mono.empty()), 123 | execute, 124 | Mono.from(connection.rollbackTransaction()).then(Mono.empty()) 125 | ).collect(Collectors.summingInt(i -> i)); 126 | }, Connection::close, (c, err) -> c.close(), Connection::close); 127 | } 128 | 129 | // Batch 130 | @GetMapping("/batch") 131 | Flux batch() { 132 | return Flux.usingWhen(this.connectionFactory.create(), connection -> { 133 | String query1 = "INSERT INTO test VALUES (50)"; 134 | String query2 = "INSERT INTO test VALUES (70)"; 135 | Function> mapper = (result) -> Mono.from(result.getRowsUpdated()); 136 | return Flux.from(connection.createBatch().add(query1).add(query2).execute()).flatMap(mapper); 137 | }, Connection::close, (c, err) -> c.close(), Connection::close); 138 | } 139 | 140 | // Error 141 | @GetMapping("/error") 142 | Flux error() { 143 | return Flux.usingWhen(this.connectionFactory.create(), connection -> { 144 | String query = "SELECT SOMETHING_WRONG();"; 145 | Flux execute = Flux.from(connection.createStatement(query).execute()); 146 | Function> mapper = (result) -> Flux.from(result.map((row, rowMetadata) -> row.get(0, Integer.class))); 147 | return execute.flatMap(mapper); 148 | }, Connection::close, (c, err) -> c.close(), Connection::close); 149 | } 150 | 151 | // Error with recovery 152 | @GetMapping("/error-recovery") 153 | Flux errorRecovery() { 154 | return Flux.usingWhen(this.connectionFactory.create(), connection -> { 155 | String query = "SELECT SOMETHING_WRONG();"; 156 | Flux execute = Flux.from(connection.createStatement(query).execute()); 157 | Function> mapper = (result) -> Flux.from(result.map((row, rowMetadata) -> row.get(0, Integer.class))); 158 | return execute.flatMap(mapper).onErrorReturn(-1); 159 | }, Connection::close, (c, err) -> c.close(), Connection::close); 160 | } 161 | 162 | // Error with Tx 163 | @GetMapping("/error-tx") 164 | Mono errorTx() { 165 | return Mono.usingWhen(this.connectionFactory.create(), connection -> { 166 | String query = "INSERT INTO test VALUES ($1)"; 167 | Flux execute = Flux.from(connection.createStatement(query).bind("$1", "ABC").execute()); 168 | Function> mapper = (result) -> Mono.from(result.getRowsUpdated()); 169 | Flux action = execute.flatMap(mapper); 170 | 171 | return Flux.concat( 172 | Mono.from(connection.beginTransaction()).then(), 173 | action, 174 | Mono.from(connection.commitTransaction()).then() 175 | ).onErrorResume(err -> 176 | Mono.from(connection.rollbackTransaction()).thenReturn(-1) 177 | ).collect(Collectors.summingInt(i -> (int) i)); 178 | }, Connection::close, (c, err) -> c.close(), Connection::close); 179 | } 180 | 181 | } 182 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/SpringAopProxyFactory.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.r2dbc.proxy.callback.BatchCallbackHandler; 4 | import io.r2dbc.proxy.callback.CallbackHandler; 5 | import io.r2dbc.proxy.callback.ConnectionCallbackHandler; 6 | import io.r2dbc.proxy.callback.ConnectionFactoryCallbackHandler; 7 | import io.r2dbc.proxy.callback.ProxyConfig; 8 | import io.r2dbc.proxy.callback.ResultCallbackHandler; 9 | import io.r2dbc.proxy.callback.StatementCallbackHandler; 10 | import io.r2dbc.proxy.core.ConnectionInfo; 11 | import io.r2dbc.proxy.core.QueryExecutionInfo; 12 | import io.r2dbc.proxy.core.StatementInfo; 13 | import io.r2dbc.spi.Batch; 14 | import io.r2dbc.spi.Connection; 15 | import io.r2dbc.spi.ConnectionFactory; 16 | import io.r2dbc.spi.Result; 17 | import io.r2dbc.spi.Statement; 18 | import io.r2dbc.spi.Wrapped; 19 | import org.aopalliance.intercept.MethodInterceptor; 20 | import org.aopalliance.intercept.MethodInvocation; 21 | 22 | import org.springframework.aop.framework.ProxyFactory; 23 | 24 | /** 25 | * {@link io.r2dbc.proxy.callback.ProxyFactory} implementation that uses spring's {@link ProxyFactory} to create proxy. 26 | * 27 | * @author Tadaya Tsuyukubo 28 | */ 29 | public class SpringAopProxyFactory implements io.r2dbc.proxy.callback.ProxyFactory { 30 | 31 | private ProxyConfig proxyConfig; 32 | 33 | public SpringAopProxyFactory(ProxyConfig proxyConfig) { 34 | this.proxyConfig = proxyConfig; 35 | } 36 | 37 | /** 38 | * Interceptor for proxy. 39 | * 40 | * Delegate the invocation to the provided {@link CallbackHandler}. 41 | */ 42 | private static class ProxyInterceptor implements MethodInterceptor { 43 | CallbackHandler callbackHandler; 44 | 45 | public ProxyInterceptor(CallbackHandler callbackHandler) { 46 | this.callbackHandler = callbackHandler; 47 | } 48 | 49 | @Override 50 | public Object invoke(MethodInvocation methodInvocation) throws Throwable { 51 | return this.callbackHandler.invoke(methodInvocation.getThis(), methodInvocation.getMethod(), methodInvocation.getArguments()); 52 | } 53 | } 54 | 55 | private T createProxy(CallbackHandler callbackHandler, Object target, Class proxyInterface) { 56 | ProxyInterceptor interceptor = new ProxyInterceptor(callbackHandler); 57 | 58 | // NOTE: This ProxyFactory will use jdk dynamic proxy. 59 | // This is because we try to make a proxy on interface, and spring's ProxyFactory 60 | // uses JdkDynamicAopProxy for it. 61 | // See logic detail on "DefaultAopProxyFactory#createAopProxy" 62 | // We could put the actual object and instruct cglib to subclass it; however, 63 | // r2dbc implementations(in this case, H2 driver implementation classes) are 64 | // final classes and cglib cannot subclass final classes. 65 | // Since this implementation is to demonstrate applying different proxy mechanism, 66 | // it is ok to use jdk dynamic proxy. 67 | 68 | ProxyFactory proxyFactory = new ProxyFactory(target); 69 | proxyFactory.addAdvice(interceptor); 70 | proxyFactory.addInterface(proxyInterface); 71 | proxyFactory.addInterface(Wrapped.class); // add this to all proxies 72 | T proxy = proxyInterface.cast(proxyFactory.getProxy()); 73 | 74 | return proxy; 75 | } 76 | 77 | @Override 78 | public ConnectionFactory wrapConnectionFactory(ConnectionFactory connectionFactory) { 79 | ConnectionFactoryCallbackHandler handler = new ConnectionFactoryCallbackHandler(connectionFactory, this.proxyConfig); 80 | return createProxy(handler, connectionFactory, ConnectionFactory.class); 81 | } 82 | 83 | @Override 84 | public Connection wrapConnection(Connection connection, ConnectionInfo connectionInfo) { 85 | ConnectionCallbackHandler handler = new ConnectionCallbackHandler(connection, connectionInfo, this.proxyConfig); 86 | return createProxy(handler, connection, Connection.class); 87 | } 88 | 89 | @Override 90 | public Batch wrapBatch(Batch batch, ConnectionInfo connectionInfo) { 91 | BatchCallbackHandler handler = new BatchCallbackHandler(batch, connectionInfo, this.proxyConfig); 92 | return createProxy(handler, batch, Batch.class); 93 | } 94 | 95 | @Override 96 | public Statement wrapStatement(Statement statement, StatementInfo statementInfo, ConnectionInfo connectionInfo) { 97 | StatementCallbackHandler handler = new StatementCallbackHandler(statement, statementInfo, connectionInfo, this.proxyConfig); 98 | return createProxy(handler, statement, Statement.class); 99 | } 100 | 101 | @Override 102 | public Result wrapResult(Result result, QueryExecutionInfo queryExecutionInfo) { 103 | ResultCallbackHandler handler = new ResultCallbackHandler(result, queryExecutionInfo, this.proxyConfig); 104 | return createProxy(handler, result, Result.class); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /listener-example/src/main/java/io/r2dbc/examples/TracingExecutionListener.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import brave.Span; 4 | import brave.Tracer; 5 | import io.r2dbc.proxy.core.*; 6 | import io.r2dbc.proxy.listener.ProxyMethodExecutionListener; 7 | 8 | import static java.util.stream.Collectors.joining; 9 | 10 | /** 11 | * Listener to create spans for R2DBC SPI operations. 12 | * 13 | * @author Tadaya Tsuyukubo 14 | */ 15 | public class TracingExecutionListener implements ProxyMethodExecutionListener { 16 | 17 | private static final String TAG_CONNECTION_ID = "connectionId"; 18 | private static final String TAG_CONNECTION_CREATE_THREAD_ID = "threadIdOnCreate"; 19 | private static final String TAG_CONNECTION_CLOSE_THREAD_ID = "threadIdOnClose"; 20 | private static final String TAG_CONNECTION_CREATE_THREAD_NAME = "threadNameOnCreate"; 21 | private static final String TAG_CONNECTION_CLOSE_THREAD_NAME = "threadNameOnClose"; 22 | private static final String TAG_THREAD_ID = "threadId"; 23 | private static final String TAG_THREAD_NAME = "threadName"; 24 | private static final String TAG_QUERIES = "queries"; 25 | private static final String TAG_BATCH_SIZE = "batchSize"; 26 | private static final String TAG_QUERY_TYPE = "type"; 27 | private static final String TAG_QUERY_SUCCESS = "success"; 28 | private static final String TAG_QUERY_MAPPED_RESULT_COUNT = "mappedResultCount"; 29 | private static final String TAG_TRANSACTION_SAVEPOINT = "savepoint"; 30 | private static final String TAG_TRANSACTION_COUNT = "transactionCount"; 31 | private static final String TAG_COMMIT_COUNT = "commitCount"; 32 | private static final String TAG_ROLLBACK_COUNT = "rollbackCount"; 33 | 34 | static final String CONNECTION_SPAN_KEY = "connectionSpan"; 35 | static final String TRANSACTION_SPAN_KEY = "transactionSpan"; 36 | static final String QUERY_SPAN_KEY = "querySpan"; 37 | 38 | private final Tracer tracer; 39 | 40 | public TracingExecutionListener(Tracer tracer) { 41 | this.tracer = tracer; 42 | } 43 | 44 | @Override 45 | public void beforeCreateOnConnectionFactory(MethodExecutionInfo methodExecutionInfo) { 46 | Span connectionSpan = this.tracer.nextSpan() 47 | .name("r2dbc:connection") 48 | .kind(Span.Kind.CLIENT) 49 | .start(); 50 | 51 | // store the span for retrieval at "afterCreateOnConnectionFactory" 52 | methodExecutionInfo.getValueStore().put("initialConnectionSpan", connectionSpan); 53 | } 54 | 55 | @Override 56 | public void afterCreateOnConnectionFactory(MethodExecutionInfo methodExecutionInfo) { 57 | // retrieve the span created at "beforeCreateOnConnectionFactory" 58 | Span connectionSpan = methodExecutionInfo.getValueStore().get("initialConnectionSpan", Span.class); 59 | 60 | Throwable thrown = methodExecutionInfo.getThrown(); 61 | if (thrown != null) { 62 | connectionSpan 63 | .error(thrown) 64 | .finish(); 65 | return; 66 | } 67 | 68 | ConnectionInfo connectionInfo = methodExecutionInfo.getConnectionInfo(); 69 | String connectionId = connectionInfo.getConnectionId(); 70 | 71 | connectionSpan 72 | .tag(TAG_CONNECTION_ID, connectionId) 73 | .tag(TAG_CONNECTION_CREATE_THREAD_ID, String.valueOf(methodExecutionInfo.getThreadId())) 74 | .tag(TAG_CONNECTION_CREATE_THREAD_NAME, methodExecutionInfo.getThreadName()) 75 | .annotate("Connection created"); 76 | 77 | // store the span in connection scoped value store 78 | connectionInfo.getValueStore().put(CONNECTION_SPAN_KEY, connectionSpan); 79 | } 80 | 81 | @Override 82 | public void afterCloseOnConnection(MethodExecutionInfo methodExecutionInfo) { 83 | ConnectionInfo connectionInfo = methodExecutionInfo.getConnectionInfo(); 84 | String connectionId = connectionInfo.getConnectionId(); 85 | Span connectionSpan = connectionInfo.getValueStore().get(CONNECTION_SPAN_KEY, Span.class); 86 | if (connectionSpan == null) { 87 | return; // already closed 88 | } 89 | Throwable thrown = methodExecutionInfo.getThrown(); 90 | if (thrown != null) { 91 | connectionSpan.error(thrown); 92 | } 93 | connectionSpan 94 | .tag(TAG_CONNECTION_ID, connectionId) 95 | .tag(TAG_CONNECTION_CLOSE_THREAD_ID, String.valueOf(methodExecutionInfo.getThreadId())) 96 | .tag(TAG_CONNECTION_CLOSE_THREAD_NAME, methodExecutionInfo.getThreadName()) 97 | .tag(TAG_TRANSACTION_COUNT, String.valueOf(connectionInfo.getTransactionCount())) 98 | .tag(TAG_COMMIT_COUNT, String.valueOf(connectionInfo.getCommitCount())) 99 | .tag(TAG_ROLLBACK_COUNT, String.valueOf(connectionInfo.getRollbackCount())) 100 | .finish(); 101 | } 102 | 103 | @Override 104 | public void beforeQuery(QueryExecutionInfo queryExecutionInfo) { 105 | String connectionId = queryExecutionInfo.getConnectionInfo().getConnectionId(); 106 | 107 | String queries = queryExecutionInfo.getQueries().stream() 108 | .map(QueryInfo::getQuery) 109 | .collect(joining(", ")); 110 | 111 | Span querySpan = this.tracer 112 | .nextSpan() 113 | .name("r2dbc:query") 114 | .kind(Span.Kind.CLIENT) 115 | .tag(TAG_CONNECTION_ID, connectionId) 116 | .tag(TAG_QUERY_TYPE, queryExecutionInfo.getType().toString()) 117 | .tag(TAG_QUERIES, queries) 118 | .start(); 119 | 120 | if (ExecutionType.BATCH == queryExecutionInfo.getType()) { 121 | querySpan.tag(TAG_BATCH_SIZE, Integer.toString(queryExecutionInfo.getBatchSize())); 122 | } 123 | 124 | // pass the query span to "afterQuery" method 125 | queryExecutionInfo.getValueStore().put(QUERY_SPAN_KEY, querySpan); 126 | } 127 | 128 | @Override 129 | public void afterQuery(QueryExecutionInfo queryExecutionInfo) { 130 | Span querySpan = queryExecutionInfo.getValueStore().get(QUERY_SPAN_KEY, Span.class); 131 | querySpan 132 | .tag(TAG_THREAD_ID, String.valueOf(queryExecutionInfo.getThreadId())) 133 | .tag(TAG_THREAD_NAME, queryExecutionInfo.getThreadName()) 134 | .tag(TAG_QUERY_SUCCESS, Boolean.toString(queryExecutionInfo.isSuccess())); 135 | 136 | Throwable thrown = queryExecutionInfo.getThrowable(); 137 | if (thrown != null) { 138 | querySpan.error(thrown); 139 | } else { 140 | querySpan.tag(TAG_QUERY_MAPPED_RESULT_COUNT, Integer.toString(queryExecutionInfo.getCurrentResultCount())); 141 | } 142 | querySpan.finish(); 143 | } 144 | 145 | @Override 146 | public void beforeBeginTransactionOnConnection(MethodExecutionInfo methodExecutionInfo) { 147 | Span transactionSpan = this.tracer.nextSpan() 148 | .name("r2dbc:transaction") 149 | .kind(Span.Kind.CLIENT) 150 | .start(); 151 | 152 | methodExecutionInfo.getConnectionInfo().getValueStore().put(TRANSACTION_SPAN_KEY, transactionSpan); 153 | } 154 | 155 | @Override 156 | public void afterCommitTransactionOnConnection(MethodExecutionInfo methodExecutionInfo) { 157 | ConnectionInfo connectionInfo = methodExecutionInfo.getConnectionInfo(); 158 | String connectionId = connectionInfo.getConnectionId(); 159 | 160 | Span transactionSpan = connectionInfo.getValueStore().get(TRANSACTION_SPAN_KEY, Span.class); 161 | if (transactionSpan != null) { 162 | transactionSpan 163 | .annotate("Commit") 164 | .tag(TAG_CONNECTION_ID, connectionId) 165 | .tag(TAG_THREAD_ID, String.valueOf(methodExecutionInfo.getThreadId())) 166 | .tag(TAG_THREAD_NAME, methodExecutionInfo.getThreadName()) 167 | .finish(); 168 | } 169 | 170 | Span connectionSpan = connectionInfo.getValueStore().get(CONNECTION_SPAN_KEY, Span.class); 171 | if (connectionSpan == null) { 172 | return; 173 | } 174 | connectionSpan.annotate("Transaction commit"); 175 | } 176 | 177 | @Override 178 | public void afterRollbackTransactionOnConnection(MethodExecutionInfo methodExecutionInfo) { 179 | ConnectionInfo connectionInfo = methodExecutionInfo.getConnectionInfo(); 180 | String connectionId = connectionInfo.getConnectionId(); 181 | 182 | Span transactionSpan = connectionInfo.getValueStore().get(TRANSACTION_SPAN_KEY, Span.class); 183 | if (transactionSpan != null) { 184 | transactionSpan 185 | .annotate("Rollback") 186 | .tag(TAG_CONNECTION_ID, connectionId) 187 | .tag(TAG_THREAD_ID, String.valueOf(methodExecutionInfo.getThreadId())) 188 | .tag(TAG_THREAD_NAME, methodExecutionInfo.getThreadName()) 189 | .finish(); 190 | } 191 | 192 | Span connectionSpan = connectionInfo.getValueStore().get(CONNECTION_SPAN_KEY, Span.class); 193 | connectionSpan.annotate("Transaction rollback"); 194 | } 195 | 196 | @Override 197 | public void afterRollbackTransactionToSavepointOnConnection(MethodExecutionInfo methodExecutionInfo) { 198 | ConnectionInfo connectionInfo = methodExecutionInfo.getConnectionInfo(); 199 | String connectionId = connectionInfo.getConnectionId(); 200 | String savepoint = (String) methodExecutionInfo.getMethodArgs()[0]; 201 | 202 | Span transactionSpan = connectionInfo.getValueStore().get(TRANSACTION_SPAN_KEY, Span.class); 203 | if (transactionSpan != null) { 204 | transactionSpan 205 | .annotate("Rollback to savepoint") 206 | .tag(TAG_TRANSACTION_SAVEPOINT, savepoint) 207 | .tag(TAG_CONNECTION_ID, connectionId) 208 | .tag(TAG_THREAD_ID, String.valueOf(methodExecutionInfo.getThreadId())) 209 | .tag(TAG_THREAD_NAME, methodExecutionInfo.getThreadName()) 210 | .finish(); 211 | } 212 | 213 | Span connectionSpan = connectionInfo.getValueStore().get(CONNECTION_SPAN_KEY, Span.class); 214 | connectionSpan.annotate("Transaction rollback to savepoint"); 215 | } 216 | 217 | } 218 | -------------------------------------------------------------------------------- /listener-example/src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: r2dbc-proxy-examples 4 | sleuth: 5 | sampler: 6 | probability: 1.0 7 | 8 | management: 9 | endpoint: 10 | metrics: 11 | enabled: true 12 | endpoints: 13 | web: 14 | exposure: 15 | include: metrics 16 | -------------------------------------------------------------------------------- /listener-example/src/test/java/io/r2dbc/examples/MetricsExecutionListenerTest.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.micrometer.core.instrument.Counter; 4 | import io.micrometer.core.instrument.Meter; 5 | import io.micrometer.core.instrument.Tag; 6 | import io.micrometer.core.instrument.Timer; 7 | import io.micrometer.core.instrument.simple.SimpleMeterRegistry; 8 | import io.r2dbc.proxy.core.DefaultValueStore; 9 | import io.r2dbc.proxy.core.ValueStore; 10 | import io.r2dbc.proxy.test.MockMethodExecutionInfo; 11 | import io.r2dbc.proxy.test.MockQueryExecutionInfo; 12 | import org.junit.jupiter.api.BeforeEach; 13 | import org.junit.jupiter.api.Test; 14 | 15 | import java.util.List; 16 | 17 | import static org.assertj.core.api.Assertions.assertThat; 18 | 19 | /** 20 | * Test for {@link MetricsExecutionListener}. 21 | * 22 | * @author Tadaya Tsuyukubo 23 | */ 24 | class MetricsExecutionListenerTest { 25 | 26 | private SimpleMeterRegistry registry; 27 | private MetricsExecutionListener listener; 28 | 29 | @BeforeEach 30 | void beforeEach() { 31 | this.registry = new SimpleMeterRegistry(); 32 | this.listener = new MetricsExecutionListener(this.registry); 33 | } 34 | 35 | @Test 36 | void createConnection() { 37 | ValueStore valueStore = new DefaultValueStore(); 38 | MockMethodExecutionInfo executionInfo = MockMethodExecutionInfo.builder().valueStore(valueStore).build(); 39 | 40 | this.listener.beforeCreateOnConnectionFactory(executionInfo); 41 | this.listener.afterCreateOnConnectionFactory(executionInfo); 42 | 43 | List meters = this.registry.getMeters(); 44 | assertThat(meters).hasSize(1) 45 | .first() 46 | .isInstanceOfSatisfying(Timer.class, (timer) -> { 47 | assertThat(timer.getId().getName()).isEqualTo("r2dbc.connection"); 48 | assertThat(timer.getId().getTags()).containsExactly(Tag.of("event", "create")); 49 | }); 50 | } 51 | 52 | @Test 53 | void commit() { 54 | MockMethodExecutionInfo executionInfo = MockMethodExecutionInfo.empty(); 55 | this.listener.afterCommitTransactionOnConnection(executionInfo); 56 | 57 | List meters = this.registry.getMeters(); 58 | assertThat(meters).hasSize(1) 59 | .first() 60 | .isInstanceOfSatisfying(Counter.class, (counter) -> { 61 | assertThat(counter.getId().getName()).isEqualTo("r2dbc.transaction"); 62 | assertThat(counter.getId().getTags()).containsExactly(Tag.of("event", "commit")); 63 | assertThat(counter.count()).isEqualTo(1); 64 | }); 65 | } 66 | 67 | @Test 68 | void rollback() { 69 | MockMethodExecutionInfo executionInfo = MockMethodExecutionInfo.empty(); 70 | this.listener.afterRollbackTransactionOnConnection(executionInfo); 71 | 72 | List meters = this.registry.getMeters(); 73 | assertThat(meters).hasSize(1) 74 | .first() 75 | .isInstanceOfSatisfying(Counter.class, (counter) -> { 76 | assertThat(counter.getId().getName()).isEqualTo("r2dbc.transaction"); 77 | assertThat(counter.getId().getTags()).containsExactly(Tag.of("event", "rollback")); 78 | assertThat(counter.count()).isEqualTo(1); 79 | }); 80 | } 81 | 82 | @Test 83 | void afterExecuteOnBatch() { 84 | MockQueryExecutionInfo executionInfo = MockQueryExecutionInfo.empty(); 85 | this.listener.afterExecuteOnBatch(executionInfo); 86 | 87 | List meters = this.registry.getMeters(); 88 | assertThat(meters).hasSize(1) 89 | .first() 90 | .isInstanceOfSatisfying(Counter.class, (counter) -> { 91 | assertThat(counter.getId().getName()).isEqualTo("r2dbc.query"); 92 | assertThat(counter.count()).isEqualTo(1); 93 | }); 94 | } 95 | 96 | @Test 97 | void afterExecuteOnStatement() { 98 | MockQueryExecutionInfo executionInfo = MockQueryExecutionInfo.empty(); 99 | this.listener.afterExecuteOnStatement(executionInfo); 100 | 101 | List meters = this.registry.getMeters(); 102 | assertThat(meters).hasSize(1) 103 | .first() 104 | .isInstanceOfSatisfying(Counter.class, (counter) -> { 105 | assertThat(counter.getId().getName()).isEqualTo("r2dbc.query"); 106 | assertThat(counter.count()).isEqualTo(1); 107 | }); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /listener-example/src/test/java/io/r2dbc/examples/QueryTimeMetricsExecutionListenerTest.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import io.micrometer.core.instrument.Timer; 4 | import io.micrometer.core.instrument.simple.SimpleMeterRegistry; 5 | import io.r2dbc.proxy.core.QueryExecutionInfo; 6 | import io.r2dbc.proxy.core.QueryInfo; 7 | import io.r2dbc.proxy.test.MockQueryExecutionInfo; 8 | import org.junit.jupiter.api.extension.ExtensionContext; 9 | import org.junit.jupiter.params.ParameterizedTest; 10 | import org.junit.jupiter.params.provider.Arguments; 11 | import org.junit.jupiter.params.provider.ArgumentsProvider; 12 | import org.junit.jupiter.params.provider.ArgumentsSource; 13 | 14 | import java.time.Duration; 15 | import java.util.concurrent.TimeUnit; 16 | import java.util.stream.Stream; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.junit.jupiter.params.provider.Arguments.arguments; 20 | 21 | /** 22 | * Test for {@link QueryTimeMetricsExecutionListener}. 23 | * 24 | * @author Tadaya Tsuyukubo 25 | */ 26 | class QueryTimeMetricsExecutionListenerTest { 27 | 28 | @ParameterizedTest 29 | @ArgumentsSource(MetricsArgumentsProvider.class) 30 | void metrics(String query, String meterName) { 31 | SimpleMeterRegistry registry = new SimpleMeterRegistry(); 32 | QueryTimeMetricsExecutionListener listener = new QueryTimeMetricsExecutionListener(registry); 33 | 34 | QueryInfo queryInfo = new QueryInfo(query); 35 | QueryExecutionInfo queryExecutionInfo = new MockQueryExecutionInfo.Builder() 36 | .queryInfo(queryInfo) 37 | .executeDuration(Duration.ofSeconds(10)) 38 | .build(); 39 | 40 | listener.afterQuery(queryExecutionInfo); 41 | 42 | Timer select = registry.get(meterName).timer(); 43 | assertThat(select.count()).isEqualTo(1); 44 | assertThat(select.totalTime(TimeUnit.SECONDS)).isEqualTo(10); 45 | } 46 | 47 | private static class MetricsArgumentsProvider implements ArgumentsProvider { 48 | 49 | @Override 50 | public Stream provideArguments(ExtensionContext context) { 51 | return Stream.of( 52 | // query, meter name 53 | arguments("SELECT ...", "r2dbc.query.select"), 54 | arguments("INSERT ...", "r2dbc.query.insert"), 55 | arguments("UPDATE ...", "r2dbc.query.update"), 56 | arguments("DELETE ...", "r2dbc.query.delete"), 57 | arguments("UPSERT ...", "r2dbc.query.other") 58 | ); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /listener-example/src/test/java/io/r2dbc/examples/TracingExecutionListenerTest.java: -------------------------------------------------------------------------------- 1 | package io.r2dbc.examples; 2 | 3 | import brave.Span; 4 | import brave.Tracer; 5 | import brave.Tracing; 6 | import brave.propagation.StrictCurrentTraceContext; 7 | import brave.test.TestSpanHandler; 8 | import io.r2dbc.proxy.core.ConnectionInfo; 9 | import io.r2dbc.proxy.core.ExecutionType; 10 | import io.r2dbc.proxy.core.QueryInfo; 11 | import io.r2dbc.proxy.core.ValueStore; 12 | import io.r2dbc.proxy.test.MockConnectionInfo; 13 | import io.r2dbc.proxy.test.MockMethodExecutionInfo; 14 | import io.r2dbc.proxy.test.MockQueryExecutionInfo; 15 | import org.junit.jupiter.api.AfterEach; 16 | import org.junit.jupiter.api.Test; 17 | 18 | import static io.r2dbc.examples.TracingExecutionListener.CONNECTION_SPAN_KEY; 19 | import static io.r2dbc.examples.TracingExecutionListener.TRANSACTION_SPAN_KEY; 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | 22 | /** 23 | * Test for {@link TracingExecutionListener}. 24 | * 25 | * @author Tadaya Tsuyukubo 26 | */ 27 | class TracingExecutionListenerTest { 28 | 29 | private StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create(); 30 | private TestSpanHandler spanHandler = new TestSpanHandler(); 31 | private Tracing tracing = Tracing.newBuilder() 32 | .currentTraceContext(currentTraceContext) 33 | .addSpanHandler(spanHandler) 34 | .build(); 35 | 36 | private Tracer tracer = tracing.tracer(); 37 | private TracingExecutionListener listener = new TracingExecutionListener(tracer); 38 | 39 | @AfterEach 40 | void afterEach() { 41 | Tracing.current().close(); 42 | } 43 | 44 | @Test 45 | void query() { 46 | ValueStore valueStore = ValueStore.create(); 47 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 48 | .connectionId("foo") 49 | .valueStore(valueStore) 50 | .build(); 51 | QueryInfo queryInfo = new QueryInfo("SELECT 1"); 52 | MockQueryExecutionInfo queryExecutionInfo = MockQueryExecutionInfo.builder() 53 | .connectionInfo(connectionInfo) 54 | .queryInfo(queryInfo) 55 | .type(ExecutionType.STATEMENT) 56 | .threadName("thread-name") 57 | .threadId(300) 58 | .isSuccess(true) 59 | .build(); 60 | 61 | this.listener.beforeQuery(queryExecutionInfo); 62 | this.listener.afterQuery(queryExecutionInfo); 63 | 64 | assertThat(this.spanHandler.spans()).hasSize(1); 65 | assertThat(this.spanHandler.get(0).name()).isEqualTo("r2dbc:query"); 66 | assertThat(this.spanHandler.get(0).tags()) 67 | .containsEntry("queries", "SELECT 1") 68 | .containsEntry("threadName", "thread-name") 69 | .containsEntry("threadId", "300") 70 | .containsEntry("success", "true") 71 | ; 72 | } 73 | 74 | @Test 75 | void createConnection() { 76 | ValueStore valueStore = ValueStore.create(); 77 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 78 | .connectionId("foo") 79 | .valueStore(valueStore) 80 | .build(); 81 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 82 | .connectionInfo(connectionInfo) 83 | .threadId(10) 84 | .threadName("thread-name") 85 | .build(); 86 | 87 | this.listener.beforeCreateOnConnectionFactory(methodExecutionInfo); 88 | this.listener.afterCreateOnConnectionFactory(methodExecutionInfo); 89 | 90 | 91 | assertThat(valueStore.get(CONNECTION_SPAN_KEY)).as("Connection span should be stored") 92 | .isNotNull().isInstanceOf(Span.class); 93 | 94 | Span span = valueStore.get(CONNECTION_SPAN_KEY, Span.class); 95 | span.finish(); 96 | 97 | assertThat(this.spanHandler.spans()).hasSize(1); 98 | assertThat(this.spanHandler.get(0).name()).isEqualTo("r2dbc:connection"); 99 | assertThat(this.spanHandler.get(0).tags()) 100 | .containsEntry("connectionId", "foo") 101 | .containsEntry("threadNameOnCreate", "thread-name") 102 | .containsEntry("threadIdOnCreate", "10") 103 | ; 104 | assertThat(this.spanHandler.get(0).containsAnnotation("Connection created")).isTrue(); 105 | } 106 | 107 | @Test 108 | void createConnectionWithError() { 109 | Exception error = new RuntimeException(); 110 | 111 | ValueStore valueStore = ValueStore.create(); 112 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 113 | .connectionId("foo") 114 | .valueStore(valueStore) 115 | .build(); 116 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 117 | .connectionInfo(connectionInfo) 118 | .threadId(10) 119 | .threadName("thread-name") 120 | .setThrown(error) 121 | .build(); 122 | 123 | this.listener.beforeCreateOnConnectionFactory(methodExecutionInfo); 124 | this.listener.afterCreateOnConnectionFactory(methodExecutionInfo); 125 | 126 | assertThat(this.spanHandler.spans()).hasSize(1); 127 | assertThat(this.spanHandler.get(0).name()).isEqualTo("r2dbc:connection"); 128 | assertThat(this.spanHandler.get(0).error()).isSameAs(error); 129 | } 130 | 131 | @Test 132 | void closeConnection() { 133 | Span span = this.tracer.nextSpan().kind(Span.Kind.CLIENT).start(); 134 | 135 | ValueStore valueStore = ValueStore.create(); 136 | valueStore.put(CONNECTION_SPAN_KEY, span); 137 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 138 | .connectionId("foo") 139 | .commitCount(10) 140 | .rollbackCount(20) 141 | .transactionCount(30) 142 | .valueStore(valueStore) 143 | .build(); 144 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 145 | .connectionInfo(connectionInfo) 146 | .threadName("thread-name") 147 | .threadId(300) 148 | .build(); 149 | 150 | this.listener.afterCloseOnConnection(methodExecutionInfo); 151 | 152 | assertThat(this.spanHandler.spans()).hasSize(1); 153 | assertThat(this.spanHandler.get(0).tags()) 154 | .containsEntry("connectionId", "foo") 155 | .containsEntry("threadNameOnClose", "thread-name") 156 | .containsEntry("threadIdOnClose", "300") 157 | .containsEntry("commitCount", "10") 158 | .containsEntry("rollbackCount", "20") 159 | .containsEntry("transactionCount", "30") 160 | ; 161 | } 162 | 163 | @Test 164 | void closeConnectionWithError() { 165 | Span span = this.tracer.nextSpan().kind(Span.Kind.CLIENT).start(); 166 | 167 | Exception error = new RuntimeException(); 168 | 169 | ValueStore valueStore = ValueStore.create(); 170 | valueStore.put(CONNECTION_SPAN_KEY, span); 171 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 172 | .connectionId("foo") 173 | .valueStore(valueStore) 174 | .build(); 175 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 176 | .connectionInfo(connectionInfo) 177 | .threadName("thread-name") 178 | .setThrown(error) 179 | .build(); 180 | 181 | this.listener.afterCloseOnConnection(methodExecutionInfo); 182 | 183 | assertThat(this.spanHandler.spans()).hasSize(1); 184 | assertThat(this.spanHandler.get(0).error()).isSameAs(error); 185 | } 186 | 187 | @Test 188 | void beginTransaction() { 189 | ValueStore valueStore = ValueStore.create(); 190 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 191 | .connectionId("foo") 192 | .valueStore(valueStore) 193 | .build(); 194 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 195 | .connectionInfo(connectionInfo) 196 | .build(); 197 | 198 | this.listener.beforeBeginTransactionOnConnection(methodExecutionInfo); 199 | 200 | Span span = valueStore.get(TRANSACTION_SPAN_KEY, Span.class); 201 | assertThat(span).as("transaction span should be stored").isNotNull(); 202 | 203 | assertThat(this.spanHandler.spans()).as("Span is not finished yet").isEmpty(); 204 | 205 | span.finish(); 206 | assertThat(this.spanHandler.get(0).name()).isEqualTo("r2dbc:transaction"); 207 | } 208 | 209 | @Test 210 | void transactionCommit() { 211 | Span connSpan = this.tracer.nextSpan().kind(Span.Kind.CLIENT).start(); 212 | Span txSpan = this.tracer.nextSpan().kind(Span.Kind.CLIENT).start(); 213 | 214 | ValueStore valueStore = ValueStore.create(); 215 | valueStore.put(CONNECTION_SPAN_KEY, connSpan); 216 | valueStore.put(TRANSACTION_SPAN_KEY, txSpan); 217 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 218 | .connectionId("foo") 219 | .valueStore(valueStore) 220 | .build(); 221 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 222 | .connectionInfo(connectionInfo) 223 | .threadId(10) 224 | .threadName("thread-name") 225 | .build(); 226 | 227 | this.listener.afterCommitTransactionOnConnection(methodExecutionInfo); 228 | 229 | // check txSpan 230 | assertThat(this.spanHandler.spans()).hasSize(1); 231 | assertThat(this.spanHandler.get(0).tags()) 232 | .containsEntry("connectionId", "foo") 233 | .containsEntry("threadName", "thread-name") 234 | .containsEntry("threadId", "10") 235 | ; 236 | assertThat(this.spanHandler.get(0).containsAnnotation("Commit")).isTrue(); 237 | 238 | // check connSpan 239 | this.spanHandler.clear(); 240 | connSpan.finish(); 241 | assertThat(this.spanHandler.spans()).hasSize(1); 242 | assertThat(this.spanHandler.get(0).containsAnnotation("Transaction commit")).isTrue(); 243 | } 244 | 245 | @Test 246 | void transactionRollback() { 247 | Span connSpan = this.tracer.nextSpan().kind(Span.Kind.CLIENT).start(); 248 | Span txSpan = this.tracer.nextSpan().kind(Span.Kind.CLIENT).start(); 249 | 250 | ValueStore valueStore = ValueStore.create(); 251 | valueStore.put(CONNECTION_SPAN_KEY, connSpan); 252 | valueStore.put(TRANSACTION_SPAN_KEY, txSpan); 253 | ConnectionInfo connectionInfo = MockConnectionInfo.builder() 254 | .connectionId("foo") 255 | .valueStore(valueStore) 256 | .build(); 257 | MockMethodExecutionInfo methodExecutionInfo = MockMethodExecutionInfo.builder() 258 | .connectionInfo(connectionInfo) 259 | .threadId(10) 260 | .threadName("thread-name") 261 | .build(); 262 | 263 | this.listener.afterRollbackTransactionOnConnection(methodExecutionInfo); 264 | 265 | // check txSpan 266 | assertThat(this.spanHandler.spans()).hasSize(1); 267 | assertThat(this.spanHandler.get(0).tags()) 268 | .containsEntry("connectionId", "foo") 269 | .containsEntry("threadName", "thread-name") 270 | .containsEntry("threadId", "10") 271 | ; 272 | assertThat(this.spanHandler.get(0).containsAnnotation("Rollback")).isTrue(); 273 | 274 | // check connSpan 275 | this.spanHandler.clear(); 276 | connSpan.finish(); 277 | assertThat(this.spanHandler.spans()).hasSize(1); 278 | assertThat(this.spanHandler.get(0).containsAnnotation("Transaction rollback")).isTrue(); 279 | } 280 | 281 | } 282 | --------------------------------------------------------------------------------