2011-11-07

Tags: cassandra , 程式語言

在建立cassandra系統時,如果不去設定每個node裡cassandra.yaml設定檔的initial_token參數,新節點會被自動指派一個token值,但是自動指派的token值通常會造成每個node在整個ring裡的距離不相等,進而導致每個node負責的partition大小不相等。如果一開始就要讓partition相等,可以利用下面的這個Java版CassandraTokenCalc(這個Sample是網路上抄來的,不知道第儿手了,別問我來源跟演算法的根據是什麼...:P)來算出合適的token,然後手動指派initial_token參數值。

public class CassandraTokenCalc {
public static void main(String[] args) {
String input = null;
int nodeAmount = 0;
try {
System.out.print("Number of Cassandra Nodes: ");
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
input = is.readLine();
nodeAmount = Integer.parseInt(input);
}
catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + input);
}
catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
BigInteger tok = new BigInteger("170141183460469231731687303715884105728");
for(int i=0; i<nodeAmount; i++){
System.out.println("Node: " + i);
System.out.println("initial_token: " + tok.multiply(BigInteger.valueOf(i)).divide(BigInteger.valueOf(nodeAmount)));
}
}
}
執行後的結果類似下面這樣
Number of Cassandra Nodes: 3
Node: 0
initial_token: 0
Node: 1
initial_token: 56713727820156410577229101238628035242
Node: 2
initial_token: 113427455640312821154458202477256070485

如果是現行已建置好的cassandra系統裡發現每個node所分配的partition不一致,可利用上面算出來的token值再配合 nodetool...move... 指令來搬移現行的token,進而達到每個partition大小一致的目標。

如果你對Python比較熟,可以參照 這篇文章算出合適的token值。