在 java aws lamba 中使用 rest temple 调用另一个 3rd party rest api 时连接超时

connection timeout while calling another 3rd party rest api using rest temple in java aws lamba

我正在尝试使用 aws lambda 中的休息模板调用第 3 方休息 api,但发生连接超时。这个第三方 api 在邮递员中工作正常。 下面是代码片段

@Override
public APIGatewayProxyResponseEvent apply(APIGatewayProxyRequestEvent request) {
    Gson gson = new Gson();
    EmailRequest emailRequest = gson.fromJson(request.getBody(),EmailRequest.class);
    System.out.println("Inside function");
    APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
    if(emailRequest!=null && emailRequest.getUserId() !=null && emailRequest.getPid()!=null) {
        Optional<UserDetail> userDetail = userRepository.findById(emailRequest.getUserId());
        Optional<Prospect> prospect = prospectRepository.findById(emailRequest.getPid());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<Prospect> entity = new HttpEntity<>(prospect.get(), httpHeaders);
        try {
            ResponseEntity<String> result = restTemplate.postForEntity(userDetail.get().getCrmUrl(), entity, String.class);
            if(result.getStatusCode().is5xxServerError()) {
                responseEvent.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
                responseEvent.withBody("Issue while sending email details");
            }
            responseEvent.setStatusCode(HttpStatus.OK.value());
        } catch (ResourceAccessException e) {
            responseEvent.setStatusCode(HttpStatus.GATEWAY_TIMEOUT.value());
            responseEvent.withBody("Rest templete time out");
            return responseEvent;
        }

        responseEvent.setStatusCode(HttpStatus.OK.value());
        responseEvent.withBody("UserId crm : " + userDetail.get().getCrmUrl() +" and Prospect first name : " + prospect.get().getFirstName());
    } else {
        responseEvent.setStatusCode(HttpStatus.BAD_REQUEST.value());
        responseEvent.withBody("Please check the request data");
    }
    return responseEvent;
}

请帮助我如何在 aws lambda 中访问第三方 rest api。

这可能是因为 VPC 中的 lambda 函数默认无法访问互联网。来自 docs:

When you connect a function to a VPC in your account, the function can't access the internet unless your VPC provides access.

克服此问题的一种流行方法是通过 NAT 网关私有子网,如以下所述: