高效、简洁的 API 性能测量 [英] Efficient, concise API performance measurement
问题描述
我想集中 API 性能测量逻辑——有没有优雅、高效的解决方案?
I'd like to centralize API performance measurement logic -- is there an elegant, efficient solution?
假设我们有这个 API:
Suppose we have this API:
public interface MyApi {
void zero();
Long one(String a);
String two(Long a, Long b);
}
我想使用一个简单的测量包装器来测量这个 API 实现的性能:
And I'd like to measure the performance of an implementation of this API using a simple measurement wrapper:
public class MyApiImpl implements MyApi{
// ...
public Long one(String a) {
Long start = System.nanoTime();
try {
return oneImpl(a);
} finally {
Measure.record(System.nanoTime()-start, "one", a);
}
}
// ...
}
但不是在每个 API 实现中重复这个测量包装器逻辑,我想集中它,例如,一个有效的注释将是一个优雅的解决方案:
but instead of repeating this measurement wrapper logic across each API implementation I'd like to centralize it, e.g., an efficient annotation would be an elegant solution:
public class MyApiImpl implements MyApi{
// ...
@Measure
public Long one(String a) {
// ...
}
// ...
}
带有 Measure
的 API 位于 Linux 开发、暂存和生产环境中,并且 24x7x365 启用.有人愿意分享好的解决方案吗?
The APIs with Measure
are in Linux development, staging, and production environments and are enabled 24x7x365. Anyone willing to share good solutions?
注意:我并不是在寻找解决"这个问题的打包软件解决方案",无论它是商业的还是开源的.问题是您如何在呼叫站点高效而优雅地解决数据收集问题,即什么是程序化解决方案,例如高效注释.
Note: I'm specifically not looking for "packaged software solution" that "solves" this problem, regardless of whether it's commercial or open-source. The question is how do you solve the gathering of data efficiently and elegantly at the call-site, i.e., what are the programmatic solutions, e.g., an efficient annotation.
推荐答案
我已经使用方面和 Dropwizard 度量做了类似的事情.首先为 Timed 注释,
I have done something similar using aspect and Dropwizard metrics. Start with creating an aspect for Timed annotation,
@Aspect
@Component
public class TimedAspect {
private MetricRegistry registry;
@Autowired
public TimedAspect(MetricRegistry registry) {
this.registry = registry;
}
@Around("@annotation(annotation) || @within(annotation)")
public Object generateMetric(
final ProceedingJoinPoint pointcut,
final Timed annotation) throws Throwable {
Timed anno = getAnnotation(pointcut, annotation);
String metricName = ...;
final Timer timer = registry.timer(metricName);
final Timer.Context context = timer.time();
try {
return pointcut.proceed();
} finally {
context.stop();
}
}
...
}
现在你可以在你班级的任何地方使用@Timed
注解,
Now you can use @Timed
annotation anywhere in your class,
public class MyApiImpl implements MyApi {
// ...
@Timed
public Long one(String a) {
// ...
}
// ...
}
我有一个工作示例这里.
这篇关于高效、简洁的 API 性能测量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!