首頁  >  文章  >  web前端  >  使用 Node.js 建立簡單的 Redis 存儲

使用 Node.js 建立簡單的 Redis 存儲

DDD
DDD原創
2024-10-22 06:22:30718瀏覽

Building a Simple Redis Store with Node.js

嘿夥伴們! ?

我一直在研究 Node.js,並決定創建一個模仿簡單版本 Redis 的輕量級記憶體中鍵值儲存。如果您想開始使用 Node.js 中的網絡,或者只是喜歡探索有趣的副業項目,那麼這個項目適合您!

?主要特點:

  • 支援的命令:
    • SET key value - 儲存鍵值對。
    • GET key - 檢索鍵的值。
    • DELETE key - 刪除鍵值對。
  • 使用 Node.js 的 net 模組建立一個 TCP 伺服器 用於處理客戶端連線。
  • 一個非常簡單的 Redis 存儲,非常適合快速測試或學習 TCP 互動!

⚙️代碼概述:

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');
});

?發生了什麼事:

  • 伺服器監聽連接埠 3001 並回應 SETGETDELETE 指令。
  • 它超級簡單明了——只需從任何 TCP 客戶端(如 telnet 或 netcat)發送命令,然後查看您的命令的實際效果!

試試看:

  1. 將程式碼儲存為 simpleRedis.js。
  2. 使用節點 simpleRedis.js 來運行它。
  3. 打開一個新終端並使用以下命令連接到它:
   telnet localhost 3001
  1. 現在,您可以與記憶體中的鍵值儲存進行互動!

例如:

SET name Hoang
GET name
>> Hoang
DELETE name
GET name
>> NULL

Github
嘗試一下! ?讓我知道您的想法或您將如何擴展它。


以上是使用 Node.js 建立簡單的 Redis 存儲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn