Created
July 8, 2020 07:49
-
-
Save mp911de/f2a921bcf4830f86854b74886c9e71ba to your computer and use it in GitHub Desktop.
Spring Data Repository Metrics
Spring Data Rep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright 2020 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 | |
* | |
* http://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 com.example.demo; | |
import java.lang.reflect.AnnotatedElement; | |
import java.lang.reflect.Method; | |
import java.util.Collections; | |
import java.util.Set; | |
import java.util.concurrent.CompletionStage; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
import io.micrometer.core.annotation.Timed; | |
import io.micrometer.core.instrument.MeterRegistry; | |
import io.micrometer.core.instrument.Timer; | |
import org.aopalliance.intercept.MethodInterceptor; | |
import org.aopalliance.intercept.MethodInvocation; | |
import org.springframework.aop.framework.ProxyFactory; | |
import org.springframework.beans.BeansException; | |
import org.springframework.beans.factory.ObjectProvider; | |
import org.springframework.beans.factory.config.BeanPostProcessor; | |
import org.springframework.boot.actuate.metrics.AutoTimer; | |
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.core.annotation.MergedAnnotationCollectors; | |
import org.springframework.core.annotation.MergedAnnotations; | |
import org.springframework.data.repository.core.RepositoryInformation; | |
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport; | |
import org.springframework.data.repository.core.support.RepositoryProxyPostProcessor; | |
import org.springframework.data.repository.util.ReactiveWrapperConverters; | |
import org.springframework.data.repository.util.ReactiveWrappers; | |
import org.springframework.util.concurrent.ListenableFuture; | |
import org.springframework.util.concurrent.ListenableFutureCallback; | |
/** | |
* @author Mark Paluch | |
*/ | |
@Configuration(proxyBeanMethods = false) | |
public class RepositoryMetricsConfiguration { | |
@Bean | |
@ConditionalOnMissingBean(RepositoryTagsProvider.class) | |
public DefaultRepositoryTagsProvider repositoryTagsProvider(ObjectProvider<RepositoryTagsContributor> contributors) { | |
return new DefaultRepositoryTagsProvider(contributors.orderedStream() | |
.collect(Collectors.toList())); | |
} | |
@Bean | |
public RepoMetricsPostProcessor repoMetricsPostProcessor(MeterRegistry registry, | |
RepositoryTagsProvider tagsProvider) { | |
return new RepoMetricsPostProcessor(registry, tagsProvider); | |
} | |
static class RepoMetricsPostProcessor implements BeanPostProcessor { | |
private final MeterRegistry registry; | |
private final RepositoryTagsProvider tagsProvider; | |
public RepoMetricsPostProcessor(MeterRegistry registry, RepositoryTagsProvider tagsProvider) { | |
this.registry = registry; | |
this.tagsProvider = tagsProvider; | |
} | |
@Override | |
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { | |
if (bean instanceof RepositoryFactoryBeanSupport) { | |
RepositoryFactoryBeanSupport<?, ?, ?> repositoryFactoryBean = (RepositoryFactoryBeanSupport<?, ?, ?>) bean; | |
MetricsMethodInterceptor interceptor = new MetricsMethodInterceptor(this.registry, repositoryFactoryBean | |
.getObjectType(), this.tagsProvider, "spring.data.repositories", AutoTimer.ENABLED); | |
repositoryFactoryBean | |
.addProxyPostProcessor(new RepositoryMetricsProxyPostProcessor(interceptor)); | |
} | |
return bean; | |
} | |
} | |
static class RepositoryMetricsProxyPostProcessor implements RepositoryProxyPostProcessor { | |
private final MetricsMethodInterceptor metricsMethodInterceptor; | |
public RepositoryMetricsProxyPostProcessor(MetricsMethodInterceptor metricsMethodInterceptor) { | |
this.metricsMethodInterceptor = metricsMethodInterceptor; | |
} | |
@Override | |
public void postProcess(ProxyFactory factory, RepositoryInformation repositoryInformation) { | |
factory.addAdvice(this.metricsMethodInterceptor); | |
} | |
} | |
static class MetricsMethodInterceptor implements MethodInterceptor { | |
private final MeterRegistry registry; | |
private final Class<?> repositoryInterface; | |
private final RepositoryTagsProvider tagsProvider; | |
private final String metricName; | |
private final AutoTimer autoTimer; | |
public MetricsMethodInterceptor(MeterRegistry registry, Class<?> repositoryInterface, RepositoryTagsProvider tagsProvider, String metricName, AutoTimer autoTimer) { | |
this.registry = registry; | |
this.repositoryInterface = repositoryInterface; | |
this.tagsProvider = tagsProvider; | |
this.metricName = metricName; | |
this.autoTimer = autoTimer; | |
} | |
@Override | |
public Object invoke(MethodInvocation invocation) throws Throwable { | |
Timer.Sample timerSample = Timer.start(this.registry); | |
try { | |
Object result = invocation.proceed(); | |
if (ReactiveWrappers.supports(invocation.getMethod().getReturnType())) { | |
Object resultToUse = ReactiveWrapperConverters | |
.doOnSuccess(result, () -> record(timerSample, invocation, result, null)); | |
return ReactiveWrapperConverters | |
.doOnError(resultToUse, (ex) -> record(timerSample, invocation, result, ex)); | |
} | |
if (result instanceof CompletionStage) { | |
return ((CompletionStage<Object>) result) | |
.whenComplete((o, throwable) -> { | |
record(timerSample, invocation, result, throwable); | |
}); | |
} | |
if (result instanceof ListenableFuture) { | |
ListenableFuture<Object> future = (ListenableFuture<Object>) result; | |
future.addCallback(new ListenableFutureCallback<Object>() { | |
@Override | |
public void onFailure(Throwable ex) { | |
record(timerSample, invocation, null, ex); | |
} | |
@Override | |
public void onSuccess(Object result) { | |
record(timerSample, invocation, result, null); | |
} | |
}); | |
return future; | |
} | |
if (result instanceof Stream) { | |
return ((Stream<Object>) result) | |
.onClose(() -> record(timerSample, invocation, result, null)); | |
} | |
record(timerSample, invocation, result, null); | |
return result; | |
} | |
catch (Throwable throwable) { | |
record(timerSample, invocation, null, throwable); | |
throw throwable; | |
} | |
} | |
private void record(Timer.Sample timerSample, MethodInvocation invocation, Object result, | |
Throwable exception) { | |
Set<Timed> annotations = getTimedAnnotations(invocation.getMethod()); | |
if (annotations.isEmpty()) { | |
if (this.autoTimer.isEnabled()) { | |
Timer.Builder builder = this.autoTimer.builder(this.metricName); | |
timerSample | |
.stop(getTimer(builder, invocation, result, exception)); | |
} | |
} | |
else { | |
for (Timed annotation : annotations) { | |
Timer.Builder builder = Timer.builder(annotation, this.metricName); | |
timerSample | |
.stop(getTimer(builder, invocation, result, exception)); | |
} | |
} | |
} | |
private Set<Timed> getTimedAnnotations(Method method) { | |
Set<Timed> methodAnnotations = findTimedAnnotations(method); | |
if (!methodAnnotations.isEmpty()) { | |
return methodAnnotations; | |
} | |
return findTimedAnnotations(method.getDeclaringClass()); | |
} | |
private Set<Timed> findTimedAnnotations(AnnotatedElement element) { | |
MergedAnnotations annotations = MergedAnnotations.from(element); | |
if (!annotations.isPresent(Timed.class)) { | |
return Collections.emptySet(); | |
} | |
return annotations.stream(Timed.class) | |
.collect(MergedAnnotationCollectors.toAnnotationSet()); | |
} | |
private Timer getTimer(Timer.Builder builder, MethodInvocation invocation, Object result, | |
Throwable exception) { | |
return builder.tags(this.tagsProvider | |
.getTags(this.repositoryInterface, invocation, result, exception)) | |
.register(this.registry); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment