Move R2DBC metrics auto-configuration into spring-boot-r2dbc

This commit is contained in:
Andy Wilkinson
2025-05-20 16:58:34 +01:00
committed by Phillip Webb
parent 9b4d5dcedf
commit 7129385ddb
6 changed files with 13 additions and 14 deletions

View File

@@ -23,6 +23,7 @@ dependencies {
optional(project(":spring-boot-project:spring-boot-autoconfigure"))
optional(project(":spring-boot-project:spring-boot-docker-compose"))
optional(project(":spring-boot-project:spring-boot-jdbc"))
optional(project(":spring-boot-project:spring-boot-metrics"))
optional(project(":spring-boot-project:spring-boot-testcontainers"))
optional("io.micrometer:micrometer-core")
optional("io.r2dbc:r2dbc-pool")

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.r2dbc.actuate.metrics.autoconfigure;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import io.r2dbc.pool.ConnectionPool;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.Wrapped;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.SimpleAutowireCandidateResolver;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.r2dbc.actuate.metrics.ConnectionPoolMetrics;
import org.springframework.boot.r2dbc.autoconfigure.R2dbcAutoConfiguration;
/**
* {@link EnableAutoConfiguration Auto-configuration} for metrics on all available
* {@link ConnectionFactory R2DBC connection factories}.
*
* @author Tadaya Tsuyukubo
* @author Stephane Nicoll
* @since 4.0.0
*/
@AutoConfiguration(after = R2dbcAutoConfiguration.class,
afterName = "org.springframework.boot.metrics.autoconfigure.CompositeMeterRegistryAutoConfiguration")
@ConditionalOnClass({ ConnectionPool.class, MeterRegistry.class })
@ConditionalOnBean({ ConnectionFactory.class, MeterRegistry.class })
public class ConnectionPoolMetricsAutoConfiguration {
@Autowired
public void bindConnectionPoolsToRegistry(ConfigurableListableBeanFactory beanFactory, MeterRegistry registry) {
SimpleAutowireCandidateResolver.resolveAutowireCandidates(beanFactory, ConnectionFactory.class)
.forEach((beanName, connectionFactory) -> {
ConnectionPool pool = extractPool(connectionFactory);
if (pool != null) {
new ConnectionPoolMetrics(pool, beanName, Tags.empty()).bindTo(registry);
}
});
}
private ConnectionPool extractPool(Object candidate) {
if (candidate instanceof ConnectionPool connectionPool) {
return connectionPool;
}
if (candidate instanceof Wrapped) {
return extractPool(((Wrapped<?>) candidate).unwrap());
}
return null;
}
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Auto-configuration for R2DBC metrics.
*/
package org.springframework.boot.r2dbc.actuate.metrics.autoconfigure;

View File

@@ -1,3 +1,4 @@
org.springframework.boot.r2dbc.actuate.metrics.autoconfigure.ConnectionPoolMetricsAutoConfiguration
org.springframework.boot.r2dbc.autoconfigure.R2dbcAutoConfiguration
org.springframework.boot.r2dbc.autoconfigure.R2dbcInitializationAutoConfiguration
org.springframework.boot.r2dbc.autoconfigure.R2dbcProxyAutoConfiguration

View File

@@ -0,0 +1,206 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.r2dbc.actuate.metrics.autoconfigure;
import java.util.Collections;
import java.util.UUID;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.r2dbc.h2.CloseableConnectionFactory;
import io.r2dbc.h2.H2ConnectionFactory;
import io.r2dbc.h2.H2ConnectionOption;
import io.r2dbc.pool.ConnectionPool;
import io.r2dbc.pool.ConnectionPoolConfiguration;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryMetadata;
import io.r2dbc.spi.Wrapped;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.metrics.autoconfigure.MetricsAutoConfiguration;
import org.springframework.boot.r2dbc.autoconfigure.R2dbcAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ConnectionPoolMetricsAutoConfiguration}.
*
* @author Tadaya Tsuyukubo
* @author Stephane Nicoll
*/
class ConnectionPoolMetricsAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.r2dbc.generate-unique-name=true", "management.metrics.use-global-registry=false")
.withBean(SimpleMeterRegistry.class)
.withConfiguration(
AutoConfigurations.of(ConnectionPoolMetricsAutoConfiguration.class, MetricsAutoConfiguration.class));
@Test
void autoConfiguredDataSourceIsInstrumented() {
this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)).run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("r2dbc.pool.acquired").gauges()).hasSize(1);
});
}
@Test
void autoConfiguredDataSourceExposedAsConnectionFactoryTypeIsInstrumented() {
this.contextRunner
.withPropertyValues(
"spring.r2dbc.url:r2dbc:pool:h2:mem:///name?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class))
.run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("r2dbc.pool.acquired").gauges()).hasSize(1);
});
}
@Test
void connectionPoolInstrumentationCanBeDisabled() {
this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class))
.withPropertyValues("management.metrics.enable.r2dbc=false")
.run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("r2dbc.pool.acquired").gauge()).isNull();
});
}
@Test
void connectionPoolExposedAsConnectionFactoryTypeIsInstrumented() {
this.contextRunner.withUserConfiguration(ConnectionFactoryConfiguration.class).run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId)
.extracting((id) -> id.getTag("name"))
.containsExactly("testConnectionPool");
});
}
@Test
void wrappedConnectionPoolExposedAsConnectionFactoryTypeIsInstrumented() {
this.contextRunner.withUserConfiguration(WrappedConnectionPoolConfiguration.class).run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId)
.extracting((id) -> id.getTag("name"))
.containsExactly("wrappedConnectionPool");
});
}
@Test
void allConnectionPoolsCanBeInstrumented() {
this.contextRunner.withUserConfiguration(MultipleConnectionPoolsConfiguration.class).run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("r2dbc.pool.acquired").meters()).map((meter) -> meter.getId().getTag("name"))
.containsOnly("standardPool", "nonDefaultPool");
});
}
@Configuration(proxyBeanMethods = false)
static class BaseConfiguration {
@Bean
SimpleMeterRegistry registry() {
return new SimpleMeterRegistry();
}
}
@Configuration(proxyBeanMethods = false)
static class ConnectionFactoryConfiguration {
@Bean
ConnectionFactory testConnectionPool() {
return new ConnectionPool(
ConnectionPoolConfiguration.builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa",
"", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1")))
.build());
}
}
@Configuration(proxyBeanMethods = false)
static class WrappedConnectionPoolConfiguration {
@Bean
ConnectionFactory wrappedConnectionPool() {
return new Wrapper(new ConnectionPool(
ConnectionPoolConfiguration.builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa",
"", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1")))
.build()));
}
static class Wrapper implements ConnectionFactory, Wrapped<ConnectionFactory> {
private final ConnectionFactory delegate;
Wrapper(ConnectionFactory delegate) {
this.delegate = delegate;
}
@Override
public ConnectionFactory unwrap() {
return this.delegate;
}
@Override
public Publisher<? extends Connection> create() {
return this.delegate.create();
}
@Override
public ConnectionFactoryMetadata getMetadata() {
return this.delegate.getMetadata();
}
}
}
@Configuration(proxyBeanMethods = false)
static class MultipleConnectionPoolsConfiguration {
@Bean
CloseableConnectionFactory connectionFactory() {
return H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", "",
Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"));
}
@Bean
ConnectionPool standardPool(ConnectionFactory connectionFactory) {
return new ConnectionPool(ConnectionPoolConfiguration.builder(connectionFactory).build());
}
@Bean(defaultCandidate = false)
ConnectionPool nonDefaultPool(ConnectionFactory connectionFactory) {
return new ConnectionPool(ConnectionPoolConfiguration.builder(connectionFactory).build());
}
@Bean(autowireCandidate = false)
ConnectionPool nonAutowirePool(ConnectionFactory connectionFactory) {
return new ConnectionPool(ConnectionPoolConfiguration.builder(connectionFactory).build());
}
}
}