ConsistentHash API
Constructor
typescript
new ConsistentHash(config?: Partial<HashConfig>)Tham số
| Param | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
| config.virtualNodes | number | 150 | Số virtual nodes cho mỗi physical node |
Phương thức
getNode(key: string): HashNode | null
Tìm node chịu trách nhiệm cho một key.
typescript
const node = hash.getNode("user:123");
console.log(node?.id); // "node-1"addNode(node: HashNode): void
Thêm node vào hash ring.
typescript
hash.addNode({ id: "node-3" });removeNode(nodeId: string): void
Xóa node khỏi hash ring.
typescript
hash.removeNode("node-1");getKeyDistribution(): Map<string, number>
Lấy số lượng keys per node.
typescript
const distribution = hash.getKeyDistribution();
console.log(distribution);
// Map { "node-0" => 365, "node-1" => 346, "node-2" => 289 }getRingSize(): number
Lấy tổng số virtual nodes trên ring.
typescript
const size = hash.getRingSize();
console.log(size); // 450 (3 nodes × 150 virtual nodes)hasNode(nodeId: string): boolean
Kiểm tra node có tồn tại trên ring không.
typescript
if (hash.hasNode("node-0")) {
// node tồn tại
}getNodes(): HashNode[]
Lấy tất cả physical nodes trên ring.
typescript
const nodes = hash.getNodes();
console.log(nodes); // [{ id: "node-0" }, { id: "node-1" }, ...]Interfaces
HashNode
typescript
interface HashNode {
id: string;
}HashConfig
typescript
interface HashConfig {
virtualNodes: number; // mặc định: 150
}