提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.tracer.core.aop; |
H |
2 |
|
|
3 |
import cn.hutool.core.map.MapUtil; |
|
4 |
import cn.hutool.core.util.StrUtil; |
|
5 |
import com.iailab.framework.tracer.core.annotation.BizTrace; |
|
6 |
import com.iailab.framework.common.util.spring.SpringExpressionUtils; |
|
7 |
import com.iailab.framework.tracer.core.util.TracerFrameworkUtils; |
|
8 |
import io.opentracing.Span; |
|
9 |
import io.opentracing.Tracer; |
|
10 |
import io.opentracing.tag.Tags; |
|
11 |
import lombok.AllArgsConstructor; |
|
12 |
import lombok.extern.slf4j.Slf4j; |
|
13 |
import org.aspectj.lang.ProceedingJoinPoint; |
|
14 |
import org.aspectj.lang.annotation.Around; |
|
15 |
import org.aspectj.lang.annotation.Aspect; |
|
16 |
|
|
17 |
import java.util.Map; |
|
18 |
|
|
19 |
import static java.util.Arrays.asList; |
|
20 |
|
|
21 |
/** |
|
22 |
* {@link BizTrace} 切面,记录业务链路 |
|
23 |
* |
|
24 |
* @author mashu |
|
25 |
*/ |
|
26 |
@Aspect |
|
27 |
@AllArgsConstructor |
|
28 |
@Slf4j |
|
29 |
public class BizTraceAspect { |
|
30 |
|
|
31 |
private static final String BIZ_OPERATION_NAME_PREFIX = "Biz/"; |
|
32 |
|
|
33 |
private final Tracer tracer; |
|
34 |
|
|
35 |
@Around(value = "@annotation(trace)") |
|
36 |
public Object around(ProceedingJoinPoint joinPoint, BizTrace trace) throws Throwable { |
|
37 |
// 创建 span |
|
38 |
String operationName = getOperationName(joinPoint, trace); |
|
39 |
Span span = tracer.buildSpan(operationName) |
|
40 |
.withTag(Tags.COMPONENT.getKey(), "biz") |
|
41 |
.start(); |
|
42 |
try { |
|
43 |
// 执行原有方法 |
|
44 |
return joinPoint.proceed(); |
|
45 |
} catch (Throwable throwable) { |
|
46 |
TracerFrameworkUtils.onError(throwable, span); |
|
47 |
throw throwable; |
|
48 |
} finally { |
|
49 |
// 设置 Span 的 biz 属性 |
|
50 |
setBizTag(span, joinPoint, trace); |
|
51 |
// 完成 Span |
|
52 |
span.finish(); |
|
53 |
} |
|
54 |
} |
|
55 |
|
|
56 |
private String getOperationName(ProceedingJoinPoint joinPoint, BizTrace trace) { |
|
57 |
// 自定义操作名 |
|
58 |
if (StrUtil.isNotEmpty(trace.operationName())) { |
|
59 |
return BIZ_OPERATION_NAME_PREFIX + trace.operationName(); |
|
60 |
} |
|
61 |
// 默认操作名,使用方法名 |
|
62 |
return BIZ_OPERATION_NAME_PREFIX |
|
63 |
+ joinPoint.getSignature().getDeclaringType().getSimpleName() |
|
64 |
+ "/" + joinPoint.getSignature().getName(); |
|
65 |
} |
|
66 |
|
|
67 |
private void setBizTag(Span span, ProceedingJoinPoint joinPoint, BizTrace trace) { |
|
68 |
try { |
|
69 |
Map<String, Object> result = SpringExpressionUtils.parseExpressions(joinPoint, asList(trace.type(), trace.id())); |
|
70 |
span.setTag(BizTrace.TYPE_TAG, MapUtil.getStr(result, trace.type())); |
|
71 |
span.setTag(BizTrace.ID_TAG, MapUtil.getStr(result, trace.id())); |
|
72 |
} catch (Exception ex) { |
|
73 |
log.error("[setBizTag][解析 bizType 与 bizId 发生异常]", ex); |
|
74 |
} |
|
75 |
} |
|
76 |
|
|
77 |
} |