在当今世界,响应请求的速度和效率对于大规模和高流量的系统至关重要。电子商务网站、社交网络和银行服务等在线平台面临着大量数据和用户请求。这种高要求不仅会给服务器和数据库带来巨大的负载,而且还会显着影响用户体验。在这种情况下,实施缓存系统可以成为提高性能和减少资源负载的有效解决方案。
在本文中,我们探索了结合 AVL 树和 Redis 的高级缓存系统的实现。该系统包括安全机制、TTL(生存时间)管理以及与 Redis 的集成,以增强性能和灵活性。目标是利用这两种技术的优点,同时减轻它们的弱点。
重要提示:本文是在人工智能的帮助下开发的。
提高记忆效率:
增强的安全性:
高级 TTL 管理:
多样化的数据结构:
增加灵活性和定制性:
增加的架构复杂性:
增加的时间开销:
数据维护与同步:
更高的开发和维护成本:
安全复杂性:
下面,我们介绍一下这个缓存系统的专业实现。此实现包括用于管理具有 TTL 功能的数据的 AVL 树和用于快速数据存储的 Redis。
首先,我们实现具有TTL管理能力的AVL树。
// src/utils/avltree.ts export class AVLNode { key: string; value: any; ttl: number; // Expiration time in milliseconds 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; 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); // Balancing the tree 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(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; } }
在本节中,我们实现了利用 AVL 树和 Redis 进行缓存管理的缓存服务。此外,我们还采用了令牌验证机制。
// src/cache/cache.service.ts import { Injectable, UnauthorizedException, InternalServerErrorException } from '@nestjs/common'; import { AVLTree } from '../utils/avltree'; import { InjectRedis, Redis } from '@nestjs-modules/ioredis'; @Injectable() export class CacheService { private avlTree: AVLTree; private authorizedTokens: Set<string> = new Set(['your_authorized_token']); // Authorized tokens constructor(@InjectRedis() private readonly redis: Redis) { this.avlTree = new AVLTree(); } validateToken(token: string): void { if (!this.authorizedTokens.has(token)) { throw new UnauthorizedException('Invalid access token'); } } async set(key: string, value: any, ttl: number, token: string): Promise<void> { this.validateToken(token); try { // Store in Redis await this.redis.set(key, JSON.stringify(value), 'PX', ttl); // Store in AVL Tree this.avlTree.insert(key, value, ttl); } catch (error) { throw new InternalServerErrorException('Failed to set cache'); } } async get(key: string, token: string): Promise<any> { this.validateToken(token); try { // First, attempt to retrieve from Redis const redisValue = await this.redis.get(key); if (redisValue) { return JSON.parse(redisValue); } // If not found in Redis, retrieve from AVL Tree const avlValue = this.avlTree.search(key); if (avlValue) { // Re-store in Redis for faster access next time // Assuming the remaining TTL is maintained in AVL Tree // For simplicity, we set a new TTL const newTtl = 60000; // 60 seconds as an example await this.redis.set(key, JSON.stringify(avlValue), 'PX', newTtl); return avlValue; } return null; } catch (error) { throw new InternalServerErrorException('Failed to get cache'); } } async delete(key: string, token: string): Promise<void> { this.validateToken(token); try { // Remove from Redis await this.redis.del(key); // Remove from AVL Tree this.avlTree.delete(key); } catch (error) { throw new InternalServerErrorException('Failed to delete cache'); } } }
控制器管理对缓存服务的 API 请求。
// src/cache/cache.controller.ts import { Controller, Get, Post, Delete, Body, Param, Query, HttpCode, HttpStatus } from '@nestjs/common'; import { CacheService } from './cache.service'; class SetCacheDto { key: string; value: any; ttl: number; // milliseconds token: string; } @Controller('cache') export class CacheController { constructor(private readonly cacheService: CacheService) {} @Post('set') @HttpCode(HttpStatus.CREATED) async setCache(@Body() body: SetCacheDto) { await this.cacheService.set(body.key, body.value, body.ttl, body.token); return { message: 'Data cached successfully' }; } @Get('get/:key') async getCache(@Param('key') key: string, @Query('token') token: string) { const value = await this.cacheService.get(key, token); return value ? { value } : { message: 'Key not found or expired' }; } @Delete('delete/:key') @HttpCode(HttpStatus.NO_CONTENT) async deleteCache(@Param('key') key: string, @Query('token') token: string) { await this.cacheService.delete(key, token); return { message: 'Key deleted successfully' }; } }
定义连接服务和控制器并注入Redis的缓存模块。
// src/cache/cache.module.ts import { Module } from '@nestjs/common'; import { CacheService } from './cache.service'; import { CacheController } from './cache.controller'; import { RedisModule } from '@nestjs-modules/ioredis'; @Module({ imports: [ RedisModule.forRoot({ config: { host: 'localhost', port: 6379, // Other Redis configurations }, }), ], providers: [CacheService], controllers: [CacheController], }) export class CacheModule {}
要在 NestJS 项目中使用 Redis,我们使用 @nestjs-modules/ioredis 包。首先,安装软件包:
npm install @nestjs-modules/ioredis ioredis
然后,在CacheModule中配置Redis,如上所示。如果您需要更高级的配置,可以使用单独的配置文件。
为了管理和验证代币,可以采用各种策略。在这个简单的实现中,令牌被维护在一个固定的集合中。对于较大的项目,建议使用 JWT(JSON Web Tokens)或其他高级安全方法。
在此实现中,DTO(数据传输对象)类用于输入验证和错误管理。此外,缓存服务利用一般错误处理来防止意外问题。
最后,我们将缓存模块添加到主应用程序模块中。
// src/utils/avltree.ts export class AVLNode { key: string; value: any; ttl: number; // Expiration time in milliseconds 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; 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); // Balancing the tree 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(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; } }
引导 NestJS 的主应用程序文件。
// src/cache/cache.service.ts import { Injectable, UnauthorizedException, InternalServerErrorException } from '@nestjs/common'; import { AVLTree } from '../utils/avltree'; import { InjectRedis, Redis } from '@nestjs-modules/ioredis'; @Injectable() export class CacheService { private avlTree: AVLTree; private authorizedTokens: Set<string> = new Set(['your_authorized_token']); // Authorized tokens constructor(@InjectRedis() private readonly redis: Redis) { this.avlTree = new AVLTree(); } validateToken(token: string): void { if (!this.authorizedTokens.has(token)) { throw new UnauthorizedException('Invalid access token'); } } async set(key: string, value: any, ttl: number, token: string): Promise<void> { this.validateToken(token); try { // Store in Redis await this.redis.set(key, JSON.stringify(value), 'PX', ttl); // Store in AVL Tree this.avlTree.insert(key, value, ttl); } catch (error) { throw new InternalServerErrorException('Failed to set cache'); } } async get(key: string, token: string): Promise<any> { this.validateToken(token); try { // First, attempt to retrieve from Redis const redisValue = await this.redis.get(key); if (redisValue) { return JSON.parse(redisValue); } // If not found in Redis, retrieve from AVL Tree const avlValue = this.avlTree.search(key); if (avlValue) { // Re-store in Redis for faster access next time // Assuming the remaining TTL is maintained in AVL Tree // For simplicity, we set a new TTL const newTtl = 60000; // 60 seconds as an example await this.redis.set(key, JSON.stringify(avlValue), 'PX', newTtl); return avlValue; } return null; } catch (error) { throw new InternalServerErrorException('Failed to get cache'); } } async delete(key: string, token: string): Promise<void> { this.validateToken(token); try { // Remove from Redis await this.redis.del(key); // Remove from AVL Tree this.avlTree.delete(key); } catch (error) { throw new InternalServerErrorException('Failed to delete cache'); } } }
实现所有组件后,您可以运行应用程序以确保其功能。
// src/cache/cache.controller.ts import { Controller, Get, Post, Delete, Body, Param, Query, HttpCode, HttpStatus } from '@nestjs/common'; import { CacheService } from './cache.service'; class SetCacheDto { key: string; value: any; ttl: number; // milliseconds token: string; } @Controller('cache') export class CacheController { constructor(private readonly cacheService: CacheService) {} @Post('set') @HttpCode(HttpStatus.CREATED) async setCache(@Body() body: SetCacheDto) { await this.cacheService.set(body.key, body.value, body.ttl, body.token); return { message: 'Data cached successfully' }; } @Get('get/:key') async getCache(@Param('key') key: string, @Query('token') token: string) { const value = await this.cacheService.get(key, token); return value ? { value } : { message: 'Key not found or expired' }; } @Delete('delete/:key') @HttpCode(HttpStatus.NO_CONTENT) async deleteCache(@Param('key') key: string, @Query('token') token: string) { await this.cacheService.delete(key, token); return { message: 'Key deleted successfully' }; } }
设置缓存:
// src/cache/cache.module.ts import { Module } from '@nestjs/common'; import { CacheService } from './cache.service'; import { CacheController } from './cache.controller'; import { RedisModule } from '@nestjs-modules/ioredis'; @Module({ imports: [ RedisModule.forRoot({ config: { host: 'localhost', port: 6379, // Other Redis configurations }, }), ], providers: [CacheService], controllers: [CacheController], }) export class CacheModule {}
获取缓存:
npm install @nestjs-modules/ioredis ioredis
删除缓存:
// src/app.module.ts import { Module } from '@nestjs/common'; import { CacheModule } from './cache/cache.module'; @Module({ imports: [CacheModule], controllers: [], providers: [], }) export class AppModule {}
银行和金融系统:
高流量电商平台:
消息和社交网络应用程序:
天气和货币兑换应用程序:
内容管理系统和媒体平台:
分析应用程序和实时仪表板:
在本文中,我们在 NestJS 框架内使用 AVL 树和 Redis 实现了高级缓存系统。该系统提供先进的 TTL 管理、基于令牌的安全性和 Redis 集成,为高需求应用程序提供了强大且灵活的解决方案。这两种技术的结合利用了两者的优势,解决了 Redis 的弱点并增强了整体缓存性能。
以上是通过 NestJS 中的高级缓存提高速度和性能:如何使用 AVL 树和 Redis的详细内容。更多信息请关注PHP中文网其他相关文章!