【问题标题】:providing timeout execution for a Spring AOP Aspect为 Spring AOP Aspect 提供超时执行
【发布时间】:2016-08-30 09:41:50
【问题描述】:

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

MyAspectlogger 方法的执行时间不应超过 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);
    }
}

【问题讨论】:

  • 请将您的代码粘贴到问题中
  • @LajosArpad 完成!,我想要做的是:避免我的 Aspect 的记录器方法需要无限时间执行。谢谢
  • 我建议使用异步日志记录,那么它可能需要多长时间。

标签: java spring spring-aop spring-async


【解决方案1】:

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

 }

【讨论】:

  • 感谢您的重播,看起来不错,但您能解释一下吗?如果 Call 方法超过 30 秒会被中断怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多