6.4.7.2. Grouping API を使用する方法
まず、グループを有効にする必要があります。Red Hat Data Grid をプログラムで設定する場合は、以下を呼び出します。
Configuration c = new ConfigurationBuilder()
.clustering().hash().groups().enabled()
.build();
または、XML を使用している場合は、以下を行います。
<distributed-cache>
<groups enabled="true"/>
</distributed-cache>
キークラスを制御できる場合(クラス定義を変更できるが、変更不可能なライブラリの一部ではない)、組み込みグループを使用することをお勧めします。intrinsic グループは、@Group アノテーションをメソッドに追加して指定します。以下に例を示します。
class User {
...
String office;
...
public int hashCode() {
// Defines the hash for the key, normally used to determine location
...
}
// Override the location by specifying a group
// All keys in the same group end up with the same owners
@Group
public String getOffice() {
return office;
}
}
}
group メソッドはStringを返す必要があります。
キークラスを制御できない場合、またはグループの決定がキークラスと直交する懸念事項である場合は、外部グループを使用することをお勧めします。外部グループは、Grouperインターフェイスを実装することによって指定されます。
public interface Grouper<T> {
String computeGroup(T key, String group);
Class<T> getKeyType();
}
同じキータイプに対して複数のGrouperクラスが構成されている場合は、それらすべてが呼び出され、前のクラスで計算された値を受け取ります。キークラスにも @Group アノテーションがある場合、最初の Grouper はアノテーション付きのメソッドによって計算されたグループを受信します。これにより、組み込みグループを使用するときに、グループをさらに細かく制御できます。Grouper 実装の例を見てみましょう。
public class KXGrouper implements Grouper<String> {
// The pattern requires a String key, of length 2, where the first character is
// "k" and the second character is a digit. We take that digit, and perform
// modular arithmetic on it to assign it to group "0" or group "1".
private static Pattern kPattern = Pattern.compile("(^k)(<a>\\d</a>)$");
public String computeGroup(String key, String group) {
Matcher matcher = kPattern.matcher(key);
if (matcher.matches()) {
String g = Integer.parseInt(matcher.group(2)) % 2 + "";
return g;
} else {
return null;
}
}
public Class<String> getKeyType() {
return String.class;
}
}
Grouper 実装は、キャッシュ設定で明示的に登録する必要があります。Red Hat Data Grid をプログラムで設定している場合は、以下を行います。
Configuration c = new ConfigurationBuilder()
.clustering().hash().groups().enabled().addGrouper(new KXGrouper())
.build();
または、XML を使用している場合は、以下を行います。
<distributed-cache>
<groups enabled="true">
<grouper class="com.acme.KXGrouper" />
</groups>
</distributed-cache>