问题
How I can provide a timeout execution to a Spring AOP Aspect ?
The logger method of MyAspect shouldn't take more time execution than 30 seconds, if not i would want to stop the method execution. How i can do this ?
MyAspect Code :
@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 Interface :
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);
}
}
回答1:
Use java.util.concurrent.Future
to check the timeout. See next example:
@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);
}
}
来源:https://stackoverflow.com/questions/39224004/providing-timeout-execution-for-a-spring-aop-aspect