0. 참고
AWS X-Ray SDK for Java – AWS X-Ray (amazon.com)
AWS X-Ray sample application – AWS X-Ray (amazon.com)
1. 구현
AWS X-Ray는 개발자가 마이크로서비스 아키텍처를 사용해 구축된 애플리케이션과 같은 어플리케이션을 분석하고 디버그에 사용하는 서비스입니다.
X-Ray SDK를 어플리케이션에 통합하고 X-Ray 에이전트를 설치하기만 하면 됩니다.
1.1 Dependency
이 예제는 Maven과 tomcat을 사용합니다.
SDK를 빌드 구성에 종속 항목으로 추가합니다.
*pom.xml*
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-apache-http</artifactId>
</dependency>
</dependencies>
1.2 Filter
Servlet filter는 하나의 Segment를 생성합니다.
들어오는(Incoming) HTTP 요청을 추적하기위해 Deployment descriptor에 Servlet filter를 추가합니다.
*web.xml*
<filter>
<filter-name>AWSXRayServletFilter</filter-name>
<filter-class>com.amazonaws.xray.javax.servlet.AWSXRayServletFilter</filter-class>
<init-param>
<param-name>fixedName</param-name>
<param-value>MyAPP</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AWSXRayServletFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
1.3 HTTP API
마이크로서비스 또는 외부 HTTP API를 호출하는 것을 추적합니다.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import com.amazonaws.xray.proxies.apache.http.HttpClientBuilder;
...
public String randomName() throws IOException {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://names.example.com/api/");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonMap = mapper.readValue(inputStream, Map.class);
String name = jsonMap.get("name");
EntityUtils.consume(entity);
return name;
} finally {
response.close();
}
}
1.4 Subsegments
Segment는 작업 단위로 데이터를 나눌 수 있습니다. 각각 나눠진 Segment는 Subsgment라고 부릅니다.
Subsgment는 요청에 대한 자세한 내용과 함께 세분화된 시간 정보를 포함합니다.
Segment에 새로운 Subsegment를 추가합니다.
import com.amazonaws.xray.AWSXRay;
...
public void saveGame(Game game) throws SessionNotFoundException {
// wrap in subsegment
Subsegment subsegment = AWSXRay.beginSubsegment("Save Game");
try {
// check session
String sessionId = game.getSession();
if (sessionModel.loadSession(sessionId) == null ) {
throw new SessionNotFoundException(sessionId);
}
mapper.save(game);
} catch (Exception e) {
subsegment.addException(e);
throw e;
} finally {
AWSXRay.endSubsegment();
}
}