providing timeout execution for a Spring AOP Aspect

久未见 提交于 2020-01-03 19:41:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!