2011年9月26日月曜日

Google App Engine for Java の非同期データストアAPIの呼び出し(その3)

Google App Engineのデータストアは、
非同期に呼び出して結果を取得することも出来ます。

英語版ドキュメントはこちら
その1はこちら,その2はこちら


Workind with Async Transactions 非同期トランザクションの使用

非同期データストアAPI呼び出しは、同期呼び出しと同じようにトランザクションに参加することができます。ここで挙げるのは、従業員の給料の額を調整し、Employeeと同じエンティティグループにSalaryAdjustmentエンティティを1つのトランザクション内で追加して書き込みます。

void giveRaise(AsyncDatastoreService datastore, Key employeeKey, long raiseAmount)
        throws Exception {
    Future txn = datastore.beginTransaction();

    // Async call to lookup the Employee entity
    Future employeeEntityFuture = datastore.get(employeeKey);

    // Create and put a SalaryAdjustment entity in parallel with the lookup
    Entity adjustmentEntity = new Entity("SalaryAdjustment", employeeKey);
    adjustmentEntity.setProperty("adjustment", raiseAmount);
    adjustmentEntity.setProperty("adjustmentDate", new Date());
    datastore.put(adjustmentEntity);

    // Fetch the result of our lookup to make the salary adjustment
    Entity employeeEntity = employeeEntityFuture.get();
    long salary = (Long) employeeEntity.getProperty("salary");
    employeeEntity.setProperty("salary", salary + raiseAmount);

    // Re-put the Employee entity with the adjusted salary.
    datastore.put(employeeEntity);
    txn.commit(); // could also call txn.commitAsync() here
}

このサンプルは、トランザクション無しの非同期呼び出しとトランザクション内での非同期呼び出しの違いを示しています。トランザクションを利用していない場合、独立した非同期呼び出しの官僚を確認する唯一の方法は、呼び出しが行われた時に戻されたFutureの値を取得するということになります。トランザクションを利用すると、Transaction.commit()の呼び出しが、トランザクション開始からコミットされる前までの全ての非同期呼び出しの結果をブロックします。

そのため、上記の例では、SalaryAdjustmentエンティティの挿入を行う非同期呼び出しがtxn.commit()を呼び出された時点では未解決の可能性があるにもかかわらず、挿入が完了するまでにコミットは起こりません。同様に、txn.commit()の代りにtxn.commitAsync()の呼び出しを選択すると、commitAsync()から返されたFutureのget()メソッド呼び出しが全ての未解決の非同期呼び出しが干渉するまでブロックします。

ノート:トランザクションは特定のスレッドに関連付けられますが、DatastoreServiceやAsyncDfatastoreServiceの特定のインスタンスには関連付けられません。これの意味するところは、あるDatastoreServiceからトランザクションを開始して、
あるAsyncDatastoreServiceから非同期呼び出しを行うと、非同期呼び出しはトランザクションに参加する、ということです。または、もっと簡潔に言えば、
DatastoreService.getCurrentTransaction()とAsyncDatastoreService.getCurrentTransaction()は常に同じトランザクションを返すということです。

インストール不要・無料のKaede翻訳ツール:
http://kaedetrans.appspot.com/

0 件のコメント:

コメントを投稿