首頁 web前端 js教程 杜絕延遲:為高需求系統實施高級且安全的緩存

杜絕延遲:為高需求系統實施高級且安全的緩存

Nov 24, 2024 am 02:20 AM

Putting an End to Delays: Implementing Advanced and Secure Caching for High-Demand Systems

介紹:

在當今世界,回應請求的速度和效率至關重要。線上商店、社交網路和銀行服務等大規模、高流量的系統面臨大量的數據和用戶請求。這種高要求不僅會為伺服器和資料庫帶來沉重的負載,還會顯著影響使用者體驗。在這種情況下,實施快取系統可以是提高效能和減少資源負載的有效解決方案。

本文討論如何實現高階快取系統,該系統利用雜湊圖和 AVL 樹的組合來實現更快的資料存取。此外,它還採用 TTL(生存時間)機制進行資料過期管理和自動資料刪除,以及輸入驗證以增強安全性。這種智慧、安全的快取系統滿足大型專案的基本需求,為提高使用者的服務速度和效率提供了強大的解決方案。

1. 用TTL實現AVL樹

為了管理資料過期,我們使用 TTL 欄位擴充 AVL 類別。此欄位指定每個資料項目的過期時間,並自動刪除過期資料。

// src/utils/avltree.ts

class AVLNode {
  key: string;
  value: any;
  ttl: number; // Time to live
  height: number;
  left: AVLNode | null;
  right: AVLNode | null;

  constructor(key: string, value: any, ttl: number) {
    this.key = key;
    this.value = value;
    this.ttl = Date.now() + ttl; // Expiry time
    this.height = 1;
    this.left = null;
    this.right = null;
  }

  isExpired(): boolean {
    return Date.now() > this.ttl;
  }
}

export class AVLTree {
  private root: AVLNode | null;

  constructor() {
    this.root = null;
  }

  private getHeight(node: AVLNode | null): number {
    return node ? node.height : 0;
  }

  private updateHeight(node: AVLNode): void {
    node.height = 1 + Math.max(this.getHeight(node.left), this.getHeight(node.right));
  }

  private rotateRight(y: AVLNode): AVLNode {
    const x = y.left!;
    y.left = x.right;
    x.right = y;
    this.updateHeight(y);
    this.updateHeight(x);
    return x;
  }

  private rotateLeft(x: AVLNode): AVLNode {
    const y = x.right!;
    x.right = y.left;
    y.left = x;
    this.updateHeight(x);
    this.updateHeight(y);
    return y;
  }

  private getBalance(node: AVLNode): number {
    return node ? this.getHeight(node.left) - this.getHeight(node.right) : 0;
  }

  insert(key: string, value: any, ttl: number): void {
    this.root = this.insertNode(this.root, key, value, ttl);
  }

  private insertNode(node: AVLNode | null, key: string, value: any, ttl: number): AVLNode {
    if (!node) return new AVLNode(key, value, ttl);

    if (key < node.key) {
      node.left = this.insertNode(node.left, key, value, ttl);
    } else if (key > node.key) {
      node.right = this.insertNode(node.right, key, value, ttl);
    } else {
      node.value = value;
      node.ttl = Date.now() + ttl;
      return node;
    }

    this.updateHeight(node);
    const balance = this.getBalance(node);

    if (balance > 1 && key < node.left!.key) return this.rotateRight(node);
    if (balance < -1 && key > node.right!.key) return this.rotateLeft(node);
    if (balance > 1 && key > node.left!.key) {
      node.left = this.rotateLeft(node.left!);
      return this.rotateRight(node);
    }
    if (balance < -1 && key < node.right!.key) {
      node.right = this.rotateRight(node.right!);
      return this.rotateLeft(node);
    }
    return node;
  }

  search(key: string): any {
    let node = this.root;
    while (node) {
      if (node.isExpired()) {
        this.delete(node.key);
        return null;
      }
      if (key === node.key) return node.value;
      node = key < node.key ? node.left : node.right;
    }
    return null;
  }

  delete(key: string): void {
    this.root = this.deleteNode(this.root, key);
  }

  private deleteNode(node: AVLNode | null, key: string): AVLNode | null {
    if (!node) return null;

    if (key < node.key) {
      node.left = this.deleteNode(node.left, key);
    } else if (key > node.key) {
      node.right = this.deleteNode(node.right, key);
    } else {
      if (!node.left || !node.right) return node.left || node.right;
      let minLargerNode = node.right;
      while (minLargerNode.left) minLargerNode = minLargerNode.left;
      node.key = minLargerNode.key;
      node.value = minLargerNode.value;
      node.ttl = minLargerNode.ttl;
      node.right = this.deleteNode(node.right, minLargerNode.key);
    }
    this.updateHeight(node);
    const balance = this.getBalance(node);

    if (balance > 1 && this.getBalance(node.left!) >= 0) return this.rotateRight(node);
    if (balance < -1 && this.getBalance(node.right!) <= 0) return this.rotateLeft(node);
    if (balance > 1 && this.getBalance(node.left!) < 0) {
      node.left = this.rotateLeft(node.left!);
      return this.rotateRight(node);
    }
    if (balance < -1 && this.getBalance(node.right!) > 0) {
      node.right = this.rotateRight(node.right!);
      return this.rotateLeft(node);
    }
    return node;
  }
}
登入後複製

2. 具有TTL和安全機制的增強型快取服務

此服務使用 AVLTree 類別來有效率且安全地管理資料。它包括一個基本的資料安全驗證機制。

// src/cache/cache.service.ts

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AVLTree } from '../utils/avltree';

@Injectable()
export class CacheService {
  private avlTree: AVLTree;
  private authorizedTokens: Set<string> = new Set(['your_authorized_token']); // Simple validation example

  constructor() {
    this.avlTree = new AVLTree();
  }

  validateToken(token: string): void {
    if (!this.authorizedTokens.has(token)) {
      throw new UnauthorizedException('Invalid access token');
    }
  }

  set(key: string, value: any, ttl: number, token: string): void {
    this.validateToken(token);
    this.avlTree.insert(key, value, ttl);
  }

  get(key: string, token: string): any {
    this.validateToken(token);
    return this.avlTree.search(key);
  }

  delete(key: string, token: string): void {
    this.validateToken(token);
    this.avlTree.delete(key);
  }
}
登入後複製

3. 帶有驗證和TTL的控制器

API 控制器使用 set、get 和 delete 方法來安全地儲存和檢索資料。

// src/cache/cache.controller.ts

import { Controller, Get, Post, Delete, Body, Param, Query } from '@nestjs/common';
import { CacheService } from './cache.service';

@Controller('cache')
export class CacheController {
  constructor(private readonly cacheService: CacheService) {}

  @Post('set')
  setCache(@Body() body: { key: string; value: any; ttl: number; token: string }) {
    this.cacheService.set(body.key, body.value, body.ttl, body.token);
    return { message: 'Data cached successfully' };
  }

  @Get('get/:key')
  getCache(@Param('key') key: string, @Query('token') token: string) {
    const value = this.cacheService.get(key, token);
    return value ? { value } : { message: 'Key not found or expired' };
  }

  @Delete('delete/:key')
  deleteCache(@Param('key') key: string, @Query('token') token: string) {
    this.cacheService.delete(key);
    return { message: 'Key deleted successfully' };
  }
}
登入後複製

快取系統的實際用例

  1. 驗證系統的會話管理:

    例如:銀行和金融系統。

  2. 用於減少請求負載的 API 快取:

    範例:天氣應用程式和貨幣兌換網站。

  3. 線上平台即時使用者狀態儲存:

    範例:WhatsApp 或 Telegram 等訊息應用程式。

  4. 線上商店中的產品資料儲存:

    範例:像亞馬遜這樣的高流量電子商務平台。

這些範例顯示此快取系統可以顯著減少資料庫和伺服器負載,從而縮短使用者的回應時間。

結論

在本文中,我們設計並實現了一個先進的快取系統,該系統結合了 AVL 樹和雜湊圖,以實現快速資料存取和伺服器效能最佳化。 TTL機制提供自動資料過期管理,而令牌驗證則確保足夠的安全性。

此智慧型快取系統高效靈活,適合具有動態和敏感資料的大規模應用,支援分散式架構中的可擴展需求。

以上是杜絕延遲:為高需求系統實施高級且安全的緩存的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1657
14
CakePHP 教程
1415
52
Laravel 教程
1309
25
PHP教程
1257
29
C# 教程
1231
24
神秘的JavaScript:它的作用以及為什麼重要 神秘的JavaScript:它的作用以及為什麼重要 Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

JavaScript的演變:當前的趨勢和未來前景 JavaScript的演變:當前的趨勢和未來前景 Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript:探索網絡語言的多功能性 JavaScript:探索網絡語言的多功能性 Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

如何使用Next.js(前端集成)構建多租戶SaaS應用程序 如何使用Next.js(前端集成)構建多租戶SaaS應用程序 Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

從C/C到JavaScript:所有工作方式 從C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

使用Next.js(後端集成)構建多租戶SaaS應用程序 使用Next.js(後端集成)構建多租戶SaaS應用程序 Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

See all articles