3

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

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

我的方面代码:

@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);
     }
}

我的服务接口:

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);
    }
}
4

1 回答 1

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

 }
于 2016-08-30T14:56:04.237 回答