Add Spring Data Repository metrics support

Add support for Spring Data Repository metrics by integrating with
Spring Data's new `RepositoryMethodInvocationListener` support.

Closes gh-22217
This commit is contained in:
Phillip Webb
2021-04-09 17:39:40 -07:00
parent 1893f935b4
commit f03f74ff0a
16 changed files with 1067 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2012-2021 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.actuate.metrics.data;
import java.lang.reflect.Method;
import java.util.function.Function;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocation;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocationResult.State;
import org.springframework.util.StringUtils;
/**
* Default {@link RepositoryTagsProvider} implementation.
*
* @author Phillip Webb
* @since 2.5.0
*/
public class DefaultRepositoryTagsProvider implements RepositoryTagsProvider {
private static final Tag EXCEPTION_NONE = Tag.of("exception", "None");
@Override
public Iterable<Tag> repositoryTags(RepositoryMethodInvocation invocation) {
Tags tags = Tags.empty();
tags = and(tags, invocation.getRepositoryInterface(), "repository", this::getSimpleClassName);
tags = and(tags, invocation.getMethod(), "method", Method::getName);
tags = and(tags, invocation.getResult().getState(), "state", State::name);
tags = and(tags, invocation.getResult().getError(), "exception", this::getExceptionName, EXCEPTION_NONE);
return tags;
}
private <T> Tags and(Tags tags, T instance, String key, Function<T, String> value) {
return and(tags, instance, key, value, null);
}
private <T> Tags and(Tags tags, T instance, String key, Function<T, String> value, Tag fallback) {
if (instance != null) {
return tags.and(key, value.apply(instance));
}
return (fallback != null) ? tags.and(fallback) : tags;
}
private String getExceptionName(Throwable error) {
return getSimpleClassName(error.getClass());
}
private String getSimpleClassName(Class<?> type) {
String simpleName = type.getSimpleName();
return (!StringUtils.hasText(simpleName)) ? type.getName() : simpleName;
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2012-2021 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.actuate.metrics.data;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import org.springframework.boot.actuate.metrics.AutoTimer;
import org.springframework.boot.actuate.metrics.annotation.TimedAnnotations;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener;
/**
* Intercepts Spring Data {@code Repository} invocations and records metrics about
* execution time and results.
*
* @author Phillip Webb
* @since 2.5.0
*/
public class MetricsRepositoryMethodInvocationListener implements RepositoryMethodInvocationListener {
private final MeterRegistry registry;
private final RepositoryTagsProvider tagsProvider;
private final String metricName;
private final AutoTimer autoTimer;
/**
* Create a new {@code MetricsRepositoryMethodInvocationListener}.
* @param registry the registry to which metrics are recorded
* @param tagsProvider provider for metrics tags
* @param metricName name of the metric to record
* @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing
*/
public MetricsRepositoryMethodInvocationListener(MeterRegistry registry, RepositoryTagsProvider tagsProvider,
String metricName, AutoTimer autoTimer) {
this.registry = registry;
this.tagsProvider = tagsProvider;
this.metricName = metricName;
this.autoTimer = (autoTimer != null) ? autoTimer : AutoTimer.DISABLED;
}
@Override
public void afterInvocation(RepositoryMethodInvocation invocation) {
Set<Timed> annotations = TimedAnnotations.get(invocation.getMethod(), invocation.getRepositoryInterface());
Iterable<Tag> tags = this.tagsProvider.repositoryTags(invocation);
long duration = invocation.getDuration(TimeUnit.NANOSECONDS);
AutoTimer.apply(this.autoTimer, this.metricName, annotations,
(builder) -> builder.tags(tags).register(this.registry).record(duration, TimeUnit.NANOSECONDS));
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2012-2021 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.actuate.metrics.data;
import io.micrometer.core.instrument.Tag;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocation;
/**
* Provides {@link Tag Tags} for Spring Data {@link RepositoryMethodInvocation Repository
* invocations}.
*
* @author Phillip Webb
* @since 2.5.0
*/
@FunctionalInterface
public interface RepositoryTagsProvider {
/**
* Provides tags to be associated with metrics for the given {@code invocation}.
* @param invocation the repository invocation
* @return tags to associate with metrics for the invocation
*/
Iterable<Tag> repositoryTags(RepositoryMethodInvocation invocation);
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2012-2021 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.actuate.metrics.data;
import java.io.IOException;
import java.lang.reflect.Method;
import io.micrometer.core.instrument.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocation;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocationResult;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocationResult.State;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DefaultRepositoryTagsProvider}.
*
* @author Phillip Webb
*/
class DefaultRepositoryTagsProviderTests {
private DefaultRepositoryTagsProvider provider = new DefaultRepositoryTagsProvider();
@Test
void repositoryTagsIncludesRepository() {
RepositoryMethodInvocation invocation = createInvocation();
Iterable<Tag> tags = this.provider.repositoryTags(invocation);
assertThat(tags).contains(Tag.of("repository", "ExampleRepository"));
}
@Test
void repositoryTagsIncludesMethod() {
RepositoryMethodInvocation invocation = createInvocation();
Iterable<Tag> tags = this.provider.repositoryTags(invocation);
assertThat(tags).contains(Tag.of("method", "findById"));
}
@Test
void repositoryTagsIncludesState() {
RepositoryMethodInvocation invocation = createInvocation();
Iterable<Tag> tags = this.provider.repositoryTags(invocation);
assertThat(tags).contains(Tag.of("state", "SUCCESS"));
}
@Test
void repositoryTagsIncludesException() {
RepositoryMethodInvocation invocation = createInvocation(new IOException());
Iterable<Tag> tags = this.provider.repositoryTags(invocation);
assertThat(tags).contains(Tag.of("exception", "IOException"));
}
@Test
void repositoryTagsWhenNoExceptionIncludesExceptionTagWithNone() {
RepositoryMethodInvocation invocation = createInvocation();
Iterable<Tag> tags = this.provider.repositoryTags(invocation);
assertThat(tags).contains(Tag.of("exception", "None"));
}
private RepositoryMethodInvocation createInvocation() {
return createInvocation(null);
}
private RepositoryMethodInvocation createInvocation(Throwable error) {
Class<?> repositoryInterface = ExampleRepository.class;
Method method = ReflectionUtils.findMethod(repositoryInterface, "findById", long.class);
RepositoryMethodInvocationResult result = mock(RepositoryMethodInvocationResult.class);
given(result.getState()).willReturn((error != null) ? State.ERROR : State.SUCCESS);
given(result.getError()).willReturn(error);
return new RepositoryMethodInvocation(repositoryInterface, method, result, 0);
}
interface ExampleRepository extends Repository<Example, Long> {
Example findById(long id);
}
static class Example {
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2012-2021 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.actuate.metrics.data;
import java.lang.reflect.Method;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.metrics.AutoTimer;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocation;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocationResult;
import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocationResult.State;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link MetricsRepositoryMethodInvocationListener}.
*
* @author Phillip Webb
*/
class MetricsRepositoryMethodInvocationListenerTests {
private static final String REQUEST_METRICS_NAME = "repository.invocations";
private SimpleMeterRegistry registry;
private MetricsRepositoryMethodInvocationListener listener;
@BeforeEach
void setup() {
MockClock clock = new MockClock();
this.registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, clock);
this.listener = new MetricsRepositoryMethodInvocationListener(this.registry,
new DefaultRepositoryTagsProvider(), REQUEST_METRICS_NAME, AutoTimer.ENABLED);
}
@Test
void afterInvocationWhenNoTimerAnnotationsAndNoAutoTimerDoesNothing() {
this.listener = new MetricsRepositoryMethodInvocationListener(this.registry,
new DefaultRepositoryTagsProvider(), REQUEST_METRICS_NAME, null);
this.listener.afterInvocation(createInvocation(NoAnnotationsRepository.class));
assertThat(this.registry.find(REQUEST_METRICS_NAME).timers()).isEmpty();
}
@Test
void afterInvocationWhenTimedMethodRecordsMetrics() {
this.listener.afterInvocation(createInvocation(TimedMethodRepository.class));
assertMetricsContainsTag("state", "SUCCESS");
assertMetricsContainsTag("tag1", "value1");
}
@Test
void afterInvocationWhenTimedClassRecordsMetrics() {
this.listener.afterInvocation(createInvocation(TimedClassRepository.class));
assertMetricsContainsTag("state", "SUCCESS");
assertMetricsContainsTag("taga", "valuea");
}
@Test
void afterInvocationWhenAutoTimedRecordsMetrics() {
this.listener.afterInvocation(createInvocation(NoAnnotationsRepository.class));
assertMetricsContainsTag("state", "SUCCESS");
}
private void assertMetricsContainsTag(String tagKey, String tagValue) {
assertThat(this.registry.get(REQUEST_METRICS_NAME).tag(tagKey, tagValue).timer().count()).isEqualTo(1);
}
private RepositoryMethodInvocation createInvocation(Class<?> repositoryInterface) {
Method method = ReflectionUtils.findMethod(repositoryInterface, "findById", long.class);
RepositoryMethodInvocationResult result = mock(RepositoryMethodInvocationResult.class);
given(result.getState()).willReturn(State.SUCCESS);
return new RepositoryMethodInvocation(repositoryInterface, method, result, 0);
}
interface NoAnnotationsRepository extends Repository<Example, Long> {
Example findById(long id);
}
interface TimedMethodRepository extends Repository<Example, Long> {
@Timed(extraTags = { "tag1", "value1" })
Example findById(long id);
}
@Timed(extraTags = { "taga", "valuea" })
interface TimedClassRepository extends Repository<Example, Long> {
Example findById(long id);
}
static class Example {
}
}