英文:
What is the best way to make operations around Spring AOP without affecting the main flow?
问题
我对Spring AOP还很陌生,我被要求根据系统上执行的几个操作将日志保存到数据库中(顺便提一下,这个系统相当庞大,涉及许多控制器、服务和实体)。我设法创建了几个通知,并获取了需要保存到日志的数据,但我担心在事务进行过程中可能会出现一些意外的异常,所以我的问题是,在这种情况下,保证主要流程继续进行,即使出现意外异常,有什么最佳实践吗?你认为使用异步并在不同的线程中管理日志记录是否是一个好主意?另外,我使用@Around在连接点流程之前和之后获取数据。谢谢!
英文:
I'm new to Spring AOP and I was asked to save logs to the DB according to several actions taken on the system (pretty big by the way with many controllers, services and entities) I managed to create several advices and get the data needed to save to the logs but I'm worried if some unexpected exception might occurs during my transactions, so my question is what's the best practice in this case to make sure the main flow continue even if there is an unexpected exception with the log saving? Do you think it would be a good idea to use Async and manage the logs saving in a different thread?
By the way an using @Around to get data before and after joinpoint flow.
Thanks!
答案1
得分: 1
你有两个选择:
-
如果您不需要将状态从前者传递到后者,可以使用
@Before
和@After
通知的组合。 -
或者,您可以使用以下基本结构的
@Around
通知:
@Around("在此处添加您的切入点表达式")
public Object myAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
try {
// 1. 在进入目标方法之前做一些操作(可选)
// 2. 执行目标方法(可选)
Object result = joinPoint.proceed();
// 3. 在获取到原始结果之后做一些操作(可选)
// 4. 返回原始或修改后的结果
return result;
}
catch (...) {
// 处理和/或记录异常(可选),然后要么
// - 重新抛出原始异常,
// - 将其包装在另一个异常中,
// - 或者返回一个常规值
}
finally {
// 无论是否发生错误,都需要执行相应操作
}
}
英文:
You have two options:
-
Either use a combination of
@Before
and@After
advice if you do not need to carry state from the former to the latter. -
Or otherwise use an
@Around
advice with this basic structure:
@Around("<your pointcut>")
public Object myAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
try {
// 1. Do something before proceeding to the target method (optional)
// 2. Proceed to target method (optional)
Object result = joinPoint.proceed();
// 3. Do something after obtaining original result (optional)
// 4. Return original or modified result
return result;
}
catch (...) {
// Handle and/or log exception (optional), then either
// - re-throw original exception,
// - wrap it in another exception or
// - return a regular value
}
finally {
// Do whatever needs to be done, no matter if an error occurs or not
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论