嘿夥伴們! ?
我一直在研究 Node.js,並決定創建一個模仿簡單版本 Redis 的輕量級記憶體中鍵值儲存。如果您想開始使用 Node.js 中的網絡,或者只是喜歡探索有趣的副業項目,那麼這個項目適合您!
const net = require('net'); class SimpleRedis { constructor() { this.store = {}; } set(key, value) { this.store[key] = value; } get(key) { return this.store[key] || null; } delete(key) { delete this.store[key]; } } // Initialize store const store = new SimpleRedis(); // Create a TCP server const server = net.createServer((socket) => { console.log('Client connected'); socket.on('data', (data) => { const command = data.toString().trim().split(' '); const action = command[0].toUpperCase(); let response = ''; switch (action) { case 'SET': const [key, value] = command.slice(1); store.set(key, value); response = `>> OK\n`; break; case 'GET': const keyToGet = command[1]; const result = store.get(keyToGet); response = result ? `>> ${result}\n` : '>> NULL\n'; break; case 'DELETE': const keyToDelete = command[1]; store.delete(keyToDelete); response = `>> OK\n`; break; default: response = '>> Invalid command\n'; } // Send the response with '>>' socket.write(response); }); socket.on('end', () => { console.log('Client disconnected'); }); }); // Start the server on port 3001 server.listen(3001, () => { console.log('Server is running on port 3001'); });
? 試試看:
telnet localhost 3001
例如:
SET name Hoang GET name >> Hoang DELETE name GET name >> NULL
Github
嘗試一下! ?讓我知道您的想法或您將如何擴展它。
以上是使用 Node.js 建立簡單的 Redis 存儲的詳細內容。更多資訊請關注PHP中文網其他相關文章!