利用aop和事件记录日志

1、定义注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @author zyl
* @description 操作注解
* @time 2019/1/17 16:36
*/
@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RUNTIME)
public @interface Operation {

OperationTypeEnum operation();

String table();
}

2、定义aop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@Aspect
@Component
@Profile({"self", "dev", "prod"})
public class OperationLogAspect {

@Autowired
private ConfigurableApplicationContext publisher;

@Pointcut("execution(* com.epet.microservices.user.service..impl..*(..))")
public void operationLogPointcut() {
}

@Around("operationLogPointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
try {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
Operation operation = targetMethod.getAnnotation(Operation.class);
if (operation != null) {
byte operationType;
switch (operation.operation()) {
case DELETE:
operationType = (byte) 3;
break;
case UPDATE:
operationType = (byte) 2;
break;
default:
operationType = (byte) 1;
}
Object[] args = joinPoint.getArgs();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
StringBuffer sb = new StringBuffer();
for (Object object : args) {
sb.append(objectMapper.writeValueAsString(object));
}
Long acId = ThreadHolderUtil.getUser() == null || ThreadHolderUtil.getUser().getAcId() == null ? 0L : ThreadHolderUtil.getUser().getAcId();
OperationLog operationLog = new OperationLog().setOperationColumn(sb.toString()).setOperationTable(operation.table()).setAcId(acId).setOperationType(operationType);
publisher.publishEvent(new OperationEvent(operationLog));
}
return joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}


}

3、定义事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @author zyl
* @description 操作日志记录
* @time 2019/1/17 17:50
*/
public class OperationEvent extends ApplicationEvent {

private OperationLog operationLog;

public OperationEvent(OperationLog operationLog) {
super(operationLog);
this.operationLog = operationLog;
}

public OperationLog getOperationLog() {
return operationLog;
}

}

4、定义事件监听器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @author zyl
* @description 订阅操作事件
* @time 2019/1/17 17:52
*/
@Component
public class OperationListener {

@Autowired
private OperationLogMapper operationLogMapper;

@EventListener
@Async
public void operation(OperationEvent operationEvent) {
OperationLog operationLog = operationEvent.getOperationLog();
int count = operationLogMapper.insert(operationLog);
System.out.println("记录日志成功" + count);
}
}