本文介紹了為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方面提供超時執行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,