非同期ビジネストランザクションの開始と終了

次に、メソッド checkoutAsync() が呼び出されるたびに「CheckoutAsync」と呼ばれるビジネストランザクションが開始されるコード例を示します。ビジネストランザクションに作成された送信元セグメントは、ビジネストランザクションでメソッド endSegment() が呼び出された場合、または try-with-resources 構成で使用されたときにクローズされた場合に終了しますtry/finally ブロックでメソッド本体をカプセル化すると、メソッド自体が例外をスローした場合でも、セグメントを終了します。それ以外の場合は、最後まで到達せずに終了します。

//The thread where the Business Transaction starts
public String checkoutAsync(List<ItemOrders> orders) {
Transaction transaction = null;
try {
transaction = AppdynamicsAgent.startTransaction("CheckoutAsync", null, EntryTypes.POJO, true);
//mark handoff to link this segment with the end segment
transaction.markHandoff(commonPayload);
/*******************
* Method Body Here
*******************/
} finally {
if (transaction != null) {
transaction.endSegment();
}
}
}

または、try-with-resources パターンがサポートされています。

//The thread where the Business Transaction starts
public String checkoutAsync(List<ItemOrders> orders) {
try (Transaction transaction = AppdynamicsAgent.startTransaction("CheckoutAsync", null, EntryTypes.POJO, true)) {
//mark handoff to link this segment with the end segment
transaction.markHandoff(commonPayload);
/*******************
* Method Body Here
*******************/
}
}

これにより、try ブロックが終了した場合にビジネストランザクションが開始されるスレッドのセグメントが終了します。ビジネストランザクション自体は、非同期ビジネストランザクションが終了するときのメソッドで終了する必要があります。

//The thread where the Business Transaction ends
public String checkoutAsyncEnd(List<ItemOrders> orders, Transaction transaction, Object commonPayload) {
//link to the originating segment
Transaction transactionSegment = AppdynamicsAgent.startSegment(commonPayload);
/*******************
* Method Body Here
*******************/
if (transactionSegment != null) {
transactionSegment.endSegment();
}
if (transaction != null) {
transaction.end();
}
}