Skip to content

Bắt đầu nhanh

Cài đặt

bash
npm install distributed-cache

Sử dụng cơ bản

typescript
import { CacheNode, ConsistentHash } from "distributed-cache";

// Tạo cache nodes
const node1 = new CacheNode("node-1", { maxSize: 10000 });
const node2 = new CacheNode("node-2", { maxSize: 10000 });
const node3 = new CacheNode("node-3", { maxSize: 10000 });

// Setup consistent hashing
const hash = new ConsistentHash();
hash.addNode({ id: "node-1" });
hash.addNode({ id: "node-2" });
hash.addNode({ id: "node-3" });

// Lưu dữ liệu
const key = "user:123";
const node = hash.getNode(key);
node?.set(key, { name: "John", email: "john@example.com" });

// Lấy dữ liệu
const value = node?.get(key);
console.log(value); // { name: "John", email: "john@example.com" }

Với TCP Server

typescript
import { CacheServer, CacheClient, CacheNode } from "distributed-cache";

// Khởi chạy server
const server = new CacheServer({ host: "127.0.0.1", port: 3000 });
server.addNode(new CacheNode("node-1", { maxSize: 10000 }));
await server.start();

// Kết nối client
const client = new CacheClient({ host: "127.0.0.1", port: 3000 });
await client.connect();

// Sử dụng cache
await client.set("product:456", { name: "iPhone", price: 999 });
const product = await client.get("product:456");
console.log(product); // { name: "iPhone", price: 999 }

await client.disconnect();
await server.stop();

Eviction Strategies

typescript
import { CacheNode } from "distributed-cache";

// LRU (mặc định) — xóa least recently used
const lru = new CacheNode("lru", {
  maxSize: 3,
  evictionPolicy: "lru",
});

// LFU — xóa least frequently used
const lfu = new CacheNode("lfu", {
  maxSize: 3,
  evictionPolicy: "lfu",
});

// FIFO — xóa entry cũ nhất
const fifo = new CacheNode("fifo", {
  maxSize: 3,
  evictionPolicy: "fifo",
});

TTL (Time To Live)

typescript
const node = new CacheNode("node-1");

// Tự hết hạn sau 60 giây
node.set("session:abc", { userId: 123 }, 60000);

// TTL tùy chỉnh cho từng key
node.set("temp:data", "value", 5000); // 5 giây

Persistence

typescript
const node = new CacheNode("node-1");

// Bật lưu trữ file
node.enablePersistence({
  filePath: "./cache-data.json",
  autoSaveInterval: 30000, // tự lưu mỗi 30s
});

// Tải từ disk
node.loadFromDisk();

// Lưu xuống disk
node.saveToDisk();

Released under the MIT License.