2.2.7. 分组 API
除了键关联服务之外,Grouping API 允许您在同一节点上并置一组条目,但无法选择实际节点。
默认情况下,使用密钥的 hashCode () 计算密钥片段。如果使用 Grouping API,Data Grid 将计算该组的片段,并使用该片段作为密钥的片段。
使用 Grouping API 时,务必要确保每个节点仍然可以计算每个密钥的所有者,而无需联系其他节点。因此,无法手动指定组。组可以不属于条目(由密钥类生成的)或 extrinsic (由外部功能生成)。
要使用 Grouping API,您必须启用组。
Configuration c = new ConfigurationBuilder() .clustering().hash().groups().enabled() .build();
<distributed-cache> <groups enabled="true"/> </distributed-cache>
如果您已控制密钥类(您可以更改类定义,而不是不可修改库的一部分),那么我们建议使用一个内部组。内部组通过向方法添加 @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;
}
}
}
组方法必须返回 String
如果您没有对密钥类控制,或者组的确定性是与密钥类相关的一个或临时性问题,我们推荐使用 extrinsic 组。通过实施组 器接口来指定 extrinsic 组。
public interface Grouper<T> {
String computeGroup(T key, String group);
Class<T> getKeyType();
}
如果为同一密钥类型配置了多个 组 类,则所有这些类都会被调用,接收上一个密钥计算的值。如果键类也具有 @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;
}
}
组器 实施必须在缓存配置中明确注册。如果您要以编程方式配置数据网格:
Configuration c = new ConfigurationBuilder() .clustering().hash().groups().enabled().addGrouper(new KXGrouper()) .build();
或者,如果您使用 XML:
<distributed-cache>
<groups enabled="true">
<grouper class="com.example.KXGrouper" />
</groups>
</distributed-cache>高级 API
AdvancedCache 有两个特定于组的方法:
-
getGroup (groupName)检索到组的缓存中的所有密钥。 -
removeGroup (groupName)删除属于组的缓存中的所有密钥。
这两种方法都迭代整个数据容器和存储(如果存在),因此当缓存包含大量小组时,它们可能会很慢。