gpt4 book ai didi

java - 抛出未捕获的异常时,Amazon AWS Lambda Java 函数需要很长时间才能完成是否正常?

转载 作者:行者123 更新时间:2023-12-05 05:19:07 25 4
gpt4 key购买 nike

当抛出未捕获的异常时,任何 Amazon AWS Lambda Java 函数花费不合理的长时间完成是否正常?请注意,这是一个关于 Java 中的 Amazon Lambdas 的一般性问题,因为我正在以非常通用的方式测试它,使用非常简单的基本功能。

例如,请考虑以下验证 PIN 的函数。如果 PIN 有效,则返回文本:PIN 正常:“A”。否则,它会抛出一个 IOException:

public class Hello implements RequestStreamHandler {    
private static final int BUFFER_SIZE = 65_536;
private static final int MAX_SIZE = 262_144;
private static final String CHARSET_UTF8 = "UTF-8";
private static final byte[] buffer = new byte[BUFFER_SIZE];
private static final ByteArrayOutputStream baos = new ByteArrayOutputStream();

public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

String input = readInputStreamToString(inputStream);

// PIN is valid.
if (input.equals("\"A\""))
writeStringToOutputStream(outputStream, "PIN is OK: " + input);

// PIN is not valid.
else
throw new IOException("PIN is wrong: " + input);
}

private String readInputStreamToString(InputStream inputStream) throws IOException {
baos.reset();
int length, total = 0;
while ((length = inputStream.read(buffer)) != -1) {
total += length;
if (total > MAX_SIZE) throw new IllegalStateException("InputStream bigger than " + MAX_SIZE + ".");
baos.write(buffer, 0, length);
}
return baos.toString(CHARSET_UTF8);
}

private void writeStringToOutputStream(OutputStream outputStream, String info) throws IOException {
byte[] chars = info.getBytes(CHARSET_UTF8);
outputStream.write(chars, 0, chars.length);
}
}

测试上面的代码:

  • 对于有效的 PIN,使用 “A” 作为测试数据。

  • 对于无效的 PIN,使用任何其他输入,例如:“B”

内存大小为 128 MB,最大使用内存为 48 MB。 PIN 码有效时,该功能非常快,不到 1 ms 即可退出。然而,当 PIN 无效时,该功能在 3 秒内超时,我得到了这个:

{
"errorMessage": "2017-10-15T21:35:58.744Z *** Task timed out after 3.00 seconds",
"errorType": "java.lang.RuntimeException"
}

然后我将超时增加到 10 秒,现在它实际上完成了大约 7.5 秒并给我一个堆栈跟踪:

{
"errorMessage": "PIN is wrong: \"B\"",
"errorType": "java.io.IOException",
"stackTrace": [ "example.Hello.handleRequest(Hello.java:83)" ]
}

我的问题:

1) lambda 函数中的异常需要 Amazon 花费那么多时间来处理是否正常?为什么?如果不是,为什么我会遇到这个问题?

2) 处理异常的推荐方法是什么?我不应该让一个函数以异常结束吗?

最佳答案

1)不要介意使用的最大内存。根据我的经验,128 MB 对于一般的 Java 函数来说是非常小的,不仅仅是由于 JVM 开销导致的异常(exception)情况。您应该将其增加到至少 4 倍。但是,请记住,异常(exception)不是免费的:

见前面的问题:

How slow are Java exceptions?

Which part of throwing an Exception is expensive?

请注意,增加资源不一定意味着增加成本,尤其是当您的函数受 CPU 限制时。您需要进行实验。

2) 您可以根据您的应用程序可能抛出的异常返回特定的 HTTP 状态代码。但是这种灵 active 会给您的代码添加一些样板。见:

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html?shortFooter=true#api-gateway-proxy-integration-lambda-function-java

关于java - 抛出未捕获的异常时,Amazon AWS Lambda Java 函数需要很长时间才能完成是否正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com