寻找在java中检测aws lambda超时(超时前几秒)的方法并对其进行测试

avkwfej4  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(353)

我当前的lambda函数正在同步调用第三方web服务。此函数偶尔会超时(当前超时设置为25s,不能进一步增加)我的代码如下:

handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
       try{
       response = calling 3rd party REST service
       }catch(Exception e){
          //handle exceptions
       }
}

1) 我想在lambda函数中通过向客户机发送自定义错误消息来自定义处理超时(跟踪时间并在实际超时之前处理几毫秒)。如何有效地使用
context.getremainingtimeinmillis()
方法跟踪同步调用运行时剩余的时间?计划异步调用context.getremainingtimeinmillis()。这是正确的方法吗?2) 测试超时自定义功能的好方法是什么?

neskvpey

neskvpey1#

我通过增加lambda超时并在一个新线程中调用我的进程并在n秒后对线程进行超时来解决问题。

ExecutorService service = Executors.newSingleThreadExecutor();
         try {
                Runnable r = () ->{
                        try {
                           myFunction();    
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                };
                f = service.submit(r);
                f.get(n, TimeUnit.MILLISECONDS);// attempt the task for n milliseconds
            }catch(TimeoutException toe){
                //custom logic
        }

相关问题