CacheServer API
Constructor
typescript
new CacheServer(config: ServerConfig)Parameters
| Param | Type | Default | Description |
|---|---|---|---|
| config.host | string | "127.0.0.1" | Bind address |
| config.port | number | 3000 | Listen port |
Methods
addNode(node: CacheNode): void
Add a cache node to the 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
Remove a node from the server.
typescript
server.removeNode("node-0");getNodeForKey(key: string): CacheNode | null
Find the node responsible for a key.
typescript
const node = server.getNodeForKey("user:123");start(): Promise<void>
Start listening for TCP connections.
typescript
await server.start();
console.log("Server running on port 3000");stop(): Promise<void>
Stop the server and close all connections.
typescript
await server.stop();
console.log("Server stopped");isRunning(): boolean
Check if the server is running.
typescript
if (server.isRunning()) {
console.log("Server is accepting connections");
}Interfaces
ServerConfig
typescript
interface ServerConfig {
host: string; // default: "127.0.0.1"
port: number; // default: 3000
}Example
typescript
import { CacheServer, CacheNode } from "distributed-cache";
const server = new CacheServer({ host: "127.0.0.1", port: 3000 });
// Add 3 nodes
for (let i = 0; i < 3; i++) {
server.addNode(new CacheNode(`node-${i}`, { maxSize: 10000 }));
}
// Start server
await server.start();
console.log("Cache server ready");
// Graceful shutdown
process.on("SIGINT", async () => {
await server.stop();
process.exit(0);
});