2016-08-30 87 views
3

如何爲Spring AOP方面提供超時執行?爲Spring AOP方面提供超時執行方面

MyAspect不應該把更多的時間執行超過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); 
    } 
} 
+0

請粘貼代碼到這個問題 –

+0

@LajosArpad做,我想做的事是:避免我的方面的記錄方法需要無限長的時間執行。謝謝 – user2602584

+0

我建議使用異步日誌記錄,然後它可以採取無論多長時間需要。 – Taylor

回答

2

使用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); 
    } 

} 
+0

感謝您的回放,它看起來像是正確的,但是你可以解釋一下嗎?如果Call方法需要超過30秒鐘,它會中斷嗎? – user2602584