我有一个Spring Boot微服务。要找到延迟问题的来源,我需要向某些对象添加跟踪。 zipking
已经配置好了,所以我想添加自定义范围。
想象一下,我有一个包含20个进行数据库调用的方法的类。要添加我的跨度,我会做这样的事情
@Repository
public class myClass {
@Autowired
private Tracer tracer;
public int myMethod1(){
Span span = tracer.createSpan("dbcall");
try{
// initial method content here
} finally {
tracer.close(span);
}
}
public int myMethod2(){
// the same as above
}
// .......
public int myMethod20(){
// the same as above
}
}
有关更聪明的方法,没有将try/finally
和span
初始化为数百次的任何想法吗?
答案 0 :(得分:2)
感谢您对我的问题发表评论,正如我建议用AOP实现的那样。 这是我的解决方案,它可能对某些人有用。
将AOP依赖关系添加到export default function shoppingCartReducer(
state: ShoppingCartStore = shoppingCartInitialState,
action: ShoppingCartActions
) {
// switch on property of action
switch (action.type) {
case AddItems:
return {
// action.payload is now CartItem
cartItems: [
...state.cartItems.filter(
cartItem => cartItem.item.id !== action.payload!.item.id
),
action.payload
]
};
case RemoveItem:
// action.payload is now number
return {
cartItems: [
...state.cartItems.filter(
cartItem => cartItem.item.id !== action.payload
)
]
};
default:
return state;
}
}
pom.xml
我创建了自定义属性<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
TrackLatency.java
我添加了使用属性调用
为每个方法添加span的方面@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackLatency {
String value() default "Track Latency Span";
}
用法:
@Aspect
@Configuration
@RequiredArgsConstructor
public class CreateNewSpanMethodAspect {
private final Tracer tracer;
@Around("@annotation(classpath.TrackLatency)")
public Object around(ProceedingJoinPoint call) throws Throwable {
Span span = tracer.createSpan(getTrackLatencyAnnotationValue(call));
try{
return call.proceed();
} finally {
tracer.close(span);
}
}
private static String getTrackLatencyAnnotationValue(ProceedingJoinPoint call){
MethodSignature signature = (MethodSignature) call.getSignature();
Method method = signature.getMethod();
TrackLatency trackLatencyAnnotation = method.getAnnotation(TrackLatency.class);
return trackLatencyAnnotation.value();
}
}