第10章 バージョンの使用

レコード(キーと値のペア)が最初にストアに挿入される際や各更新の際、一意のバージョン・トークンが割り当てられます。バージョンは、ストアにレコードを書き込んだメソッド(KVStore.put()など)によって必ず返されます。バージョン情報は、ストアからレコードを取得するメソッドによっても返されます。

バージョンが重要である理由は2つあります。

  1. 更新や削除を行う場合、レコードの値が変更されていない場合にのみ操作を行うことが重要な場合があります。これは、同時にレコードを操作するスレッドやプロセスが複数存在可能なアプリケーションでは特に有用です。この場合、レコードを読み取り、バージョンを取得します。その後、格納操作を行いますが、バージョンが変更されていない場合にのみ格納を進めることができます。これを保証するには、KVStore.putIfVersion()またはKVStore.deleteIfVersion()を使用します。

  2. クライアントが以前に書き込まれた値を読み取る際、読取り操作をサービスするOracle NoSQL Databaseノードが以前の書込み情報で更新されていることを確認することが重要な場合があります。これは、以前に書き込まれた値のバージョンを一貫性パラメータとして読取り操作に渡すことで行えます。一貫性の使用の詳細は、「一貫性保証」を参照してください。

バージョンは、Versionクラスを使用して管理されます。別のカプセル化クラス(KeyValueVersionValueVersionなど)の一部として返される場合もあります。

次のサンプル・コードでは、レコードを取得し、バージョンが変更されていない場合のみ、そのレコードを格納します。

package kvstore.basicExample;

...

import oracle.kv.Key;
import oracle.kv.Value;
import oracle.kv.ValueVersion;
import java.util.ArrayList;

...

ArrayList<String> majorComponents = new ArrayList<String>();
ArrayList<String> minorComponents = new ArrayList<String>();

...

// Define the major and minor path components for the key
majorComponents.add("Smith");
majorComponents.add("Bob");

minorComponents.add("phonenumber");

// Create the key
Key myKey = Key.createKey(majorComponents, minorComponents);

// Now retrieve the record. Note that we do not show the creation of 
// the kvstore handle here.

ValueVersion vv = kvstore.get(myKey);
Value value = vv.getValue();
Version version = vv.getVersion();

...

///////////////////////////////////////////////////////////
////////////// Do work on the value here //////////////////
///////////////////////////////////////////////////////////

...

// Put if the version is correct. Notice that here we examine
// the return code. If it is null, that means that the put was
// unsuccessful, probably because the record was changed elsewhere. 
// In this case, you could retry the entire get/putIfVersion 
// operation.
Version newVersion = kvstore.putIfVersion(myKey, value, version); 
if (newVersion == null) {
    // Unsuccessful. Someone else probably modified the record.
}