AWS Lambda
开发人员指南

在 AWS Lambda 中检测 Java 代码

在 Java 中,您可以让 Lambda 向 X-Ray 发送子分段,显示您的函数对其他 AWS 服务进行的下游调用的相关信息。要利用此功能,请在您的部署程序包中包括适用于 Java 的 AWS X-Ray 开发工具包。无需更改代码。只要您使用的 AWS 开发工具包版本为 1.11.48 或更高版本,则不需要添加任何其他代码行,就可以跟踪您的函数的下游调用。

AWS 开发工具包将动态导入 X-Ray 开发工具包,针对您的函数进行的下游调用发送子分段。您可以使用适用于 Java 的 X-Ray 开发工具包检测代码,从而发送自定义子分段和/或在 X-Ray 分段中添加注释。

以下示例使用适用于 Java 的 X-Ray 开发工具包检测 Lambda 函数,以发送自定义子分段并将自定义注释发送到 X-Ray:

package uptime; import java.io.IOException; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.proxies.apache.http.HttpClientBuilder; public class Hello { private static final Log logger = LogFactory.getLog(Hello.class); private static final AmazonDynamoDB dynamoClient; private static final HttpClient httpClient; static { dynamoClient = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); httpClient = HttpClientBuilder.create().build(); } public void checkUptime(Context context) { AWSXRay.createSubsegment("makeRequest", (subsegment) -> { HttpGet request = new HttpGet("https://aws.amazon.com/"); boolean is2xx = false; try { HttpResponse response = httpClient.execute(request); is2xx = (response.getStatusLine().getStatusCode() / 100) == 2; subsegment.putAnnotation("responseCode", response.getStatusLine().getStatusCode()); } catch (IOException ioe) { logger.error(ioe); } Map<String, AttributeValue> item = new HashMap<>(); item.put("Timestamp", new AttributeValue().withN("" + Instant.now().getEpochSecond())); item.put("2xx", new AttributeValue().withBOOL(is2xx)); dynamoClient.putItem("amazon-2xx", item); }); } }

以下是上述代码发送的跟踪的样子 (同步调用):