为Spring AOP Aspect提供超时执行

时间:2016-08-30 09:41:50

标签: java spring spring-aop spring-async

我如何为Spring AOP Aspect提供超时执行?

MyAspect 记录器方法不应该花费超过30秒的执行时间,否则我会想要停止方法执行。我怎么能这样做?

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界面:

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 个答案:

答案 0 :(得分: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);
    }

 }