Skip to content

CacheServer API

Constructor

typescript
new CacheServer(config: ServerConfig)

Tham số

ParamKiểuMặc địnhMô tả
config.hoststring"127.0.0.1"Địa chỉ bind
config.portnumber3000Port lắng nghe

Phương thức

addNode(node: CacheNode): void

Thêm cache node vào server.

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

const server = new CacheServer({ host: "127.0.0.1", port: 3000 });
server.addNode(new CacheNode("node-0", { maxSize: 10000 }));
server.addNode(new CacheNode("node-1", { maxSize: 10000 }));

removeNode(nodeId: string): void

Xóa node khỏi server.

typescript
server.removeNode("node-0");

getNodeForKey(key: string): CacheNode | null

Tìm node chịu trách nhiệm cho key.

typescript
const node = server.getNodeForKey("user:123");

start(): Promise<void>

Bắt đầu lắng nghe kết nối TCP.

typescript
await server.start();
console.log("Server đang chạy trên port 3000");

stop(): Promise<void>

Dừng server và đóng tất cả kết nối.

typescript
await server.stop();
console.log("Server đã dừng");

isRunning(): boolean

Kiểm tra server có đang chạy không.

typescript
if (server.isRunning()) {
  console.log("Server đang chấp nhận kết nối");
}

Interfaces

ServerConfig

typescript
interface ServerConfig {
  host: string; // mặc định: "127.0.0.1"
  port: number; // mặc định: 3000
}

Ví dụ

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

const server = new CacheServer({ host: "127.0.0.1", port: 3000 });

// Thêm 3 nodes
for (let i = 0; i < 3; i++) {
  server.addNode(new CacheNode(`node-${i}`, { maxSize: 10000 }));
}

// Khởi chạy server
await server.start();
console.log("Cache server sẵn sàng");

// Graceful shutdown
process.on("SIGINT", async () => {
  await server.stop();
  process.exit(0);
});

Released under the MIT License.