AWS API网关WebSocket是什么?

1cklez4t  于 5个月前  发布在  其他
关注(0)|答案(3)|浏览(86)

如何防止带有Lambda Java后端的API网关WebSocket API在30秒后超时?
AWS API Gateway和re:invent视频提到使用ping或heartbeats来保持WebSocket连接,但我还没有找到一个直接的工作示例(Java)。前端使用HTML 5 Websockets(vanilla JavaScript)。
我在Java中包含了我的Lambda测试驱动程序。它会导致API网关WS API在30秒后超时,如文档所示。如果您删除延迟,驱动程序将成功返回。感谢任何帮助.

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestWSClient implements RequestStreamHandler {

    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {
        try {
            //
            // How do we keep API Gateway from timing out after 30 seconds?
            // Is something like this even needed in the lambda?
            //
            new Thread(() -> {
                while(true) {    
                    try {
                        // Ping client every 15 seconds
                        Thread.sleep(15000);
                        //outputStream.write(); // What to write -- 0x89 0x00?
                        outputStream.flush();
                    } catch(Exception e) { e.printStackTrace(); }
                }
            }).start();

            //
            // Simulate long processing time or streaming
            //
            // NOTE: commenting sleep enables service to return w/o a timeout
            //       connection from API Gateway
            //
            try { Thread.sleep(60000); } catch(Exception e) {}

            var response = Map.of(
                "statusCode", 200,
                "headers", Map.of("Content-Type", "text/csv"),
                "body", "Hello,World"
            );

            ObjectMapper om = new ObjectMapper();

            outputStream.write(om.writeValueAsBytes(response));
            outputStream.flush();
        } catch(Exception e) { e.printStackTrace(); }
        finally { try { outputStream.close(); } catch(Exception e) {} }
    }
}

字符串

6qftjkof

6qftjkof1#

我不认为我正确理解了你的问题,但这里是如何WebSocket API在我的经验工作。客户端<-(1)-> API网关<-(2)-> Lambda
1)是Web Socket连接,它最多保持打开2小时,空闲超时为10分钟,如此处所述。https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html
2)使用@connection https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html管理通信
我相信您希望使用@connection从lambda与您的API Gateway进行对话。

yx2lnoni

yx2lnoni2#

我也遇到了同样的问题。我发现即使WebSocket连接打开到2小时,API(第一个lambda调用)的处理也会在29秒内超时。
为了解决这个问题,你必须使用一个lambda策略。因此,创建一个代理,它将接收输入并通过SNS主题或SQS队列调用所需的lambda。
有关更多信息,此链接非常有用:https://repost.aws/questions/QUFXpcneknSgmhseduEh18dw/api-gateway-websocket-api-30s-timeout

np8igboo

np8igboo3#

Lambda调用AWS ApiGatewayManagementApi SDK提供的postToConnection函数似乎需要NAT网关。
遗憾的是,关于Websockets API或API网关,没有在任何地方指定此要求。
this页面上搜索'NAT',然后阅读以下句子:

相关问题