providing timeout execution for a Spring AOP Aspect(为Spring AOP方面提供超时执行)
问题描述
如何为Spring AOP方面提供超时执行?
MyAspect的记录器方法的执行时间不应超过30秒,如果不超过30秒,我将希望停止该方法的执行。我如何才能做到这一点?
MyAspect代码:
@Aspect
@Component
public class MyAspect {
@Autowired
private myService myService;
@AfterReturning(pointcut = "execution(* xxxxx*(..))", returning = "paramOut")
public void logger(final JoinPoint jp, Object paramOut){
Event event = (Event) paramOut;
myService.save(event);
}
}
myService接口:
public interface myService {
void save(Event event);
}
myServiceImpl:
@Service
@Transactional
public class myServiceImpl implements myService {
@PersistenceContext
private EntityManager entityManager;
@Override
public void save(Event event) {
entityManager.persist(event);
}
}
推荐答案
使用java.util.concurrent.Future
查看超时。请参见下一个示例:
@AfterReturning(pointcut = "execution(* xxxxx*(..))", returning = "paramOut")
public void logger(final JoinPoint jp, Object paramOut){
Event event = (Event) paramOut;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new Callable<Void>() {
public Void call() throws Exception {
myService.save(event);
return null;
}
});
try
{
future.get(30, TimeUnit.SECONDS);
}
catch(InterruptedException | ExecutionException | TimeoutException e){
//do something or log it
} finally {
future.cancel(true);
}
}
这篇关于为Spring AOP方面提供超时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!