发布于 2026-01-06 7 阅读
0

使用 Redis 和 Express.js (TypeScript) DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

使用 Express.js (TypeScript) 和 Redis

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

图片描述
Redis 通过提供高性能的缓存和数据存储解决方案,与 Express.js 相辅相成,能够提升 Web 应用程序的速度、可扩展性和功能性。通过将 Redis 集成到 Express.js 项目中,您可以优化数据访问、处理实时功能并提高应用程序的整体性能。

Redis 经常与 Express.js 一起使用,原因有很多,Redis 和 Express.js 的结合可以为 Web 应用程序开发带来诸多好处:

  1. 缓存:Redis 是一个内存数据存储系统,提供极快的读写速度。与 Express.js 集成后,Redis 可用于缓存频繁访问的数据,从而减轻应用程序数据库的负载并提升响应速度。这对于读取操作量大的应用程序尤为有用,例如获取用户资料、产品详情或频繁更新的数据。

  2. 会话管理:Redis 通常用于 Express.js 应用中的会话管理。将会话数据存储在 Redis 中,可以高效地跨应用的多个实例管理用户会话。即使用户被重定向到不同的服务器,或者应用进行横向扩展,也能确保用户始终保持身份验证状态。

  3. 实时功能:Redis 支持发布/订阅消息机制,使其成为在 Express.js 应用中构建实时功能的理想选择。您可以利用 Redis 的发布/订阅功能向已连接的客户端广播消息,从而实现诸如实时聊天、通知和实时更新等功能。

  4. 速率限制和请求节流:Redis 可用于在 Express.js 应用中实现速率限制和请求节流机制。通过将请求数据和时间戳存储在 Redis 中,您可以控制客户端访问特定路由的速率,从而防止滥用并确保 API 的公平使用。

  5. 任务队列:Redis 可以用作后台处理和作业管理的任务队列。您可以使用 Redis 对任务进行入队和出队操作,从而更轻松地异步处理耗时的任务,例如发送电子邮件、处理上传的文件或执行批量操作。

  6. 快速数据访问:Redis 的内存特性使其能够提供亚毫秒级的数据检索响应时间。当您需要快速获取渲染网页或响应 API 请求所需的数据时,这将非常有用。Express.js 可以利用 Redis 为客户端快速提供数据。

  7. 分布式缓存:在 Express.js 应用运行于多台服务器或采用微服务架构的场景中,Redis 可以作为集中式缓存层,供所有实例访问。这确保了所有实例的缓存数据一致性,从而提升了应用的可扩展性。

  8. 灵活的数据结构:Redis 支持多种数据结构,例如字符串、列表、集合、哈希表等等。这种灵活性使您可以根据特定用例对数据进行建模,从而更轻松地在 Express.js 应用程序中处理复杂的数据结构。

  9. 持久化:Redis 可以配置为将数据持久化到磁盘,从而在保持内存存储速度优势的同时,为关键数据提供持久性。这使其非常适合数据完整性至关重要的应用场景。

第一步:前提条件和安装

开始之前,请确保您已具备以下先决条件:

  1. 您的机器上已安装Node.js和npm。
  2. 对 TypeScript 和 Express.js 有基本的了解。
  3. 本地已安装 Redis 或可访问 Redis 服务器。

现在,让我们来设置项目:

1. 为你的项目创建一个新目录,并在终端中导航到该目录:



mkdir redis-express-ts
cd redis-express-ts


Enter fullscreen mode Exit fullscreen mode

2. 使用 TypeScript 初始化一个新的 Node.js 项目:



npm init -y
npm install typescript ts-node @types/node --save-dev


Enter fullscreen mode Exit fullscreen mode

3. 在项目根目录下创建一个 TypeScript 配置文件 (tsconfig.json):



{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}


Enter fullscreen mode Exit fullscreen mode

4. 创建一个src目录来存放你的 TypeScript 代码:



mkdir src


Enter fullscreen mode Exit fullscreen mode

5.安装Express.js应用程序所需的软件包:



npm install express body-parser --save
npm install @types/express @types/body-parser --save-dev


Enter fullscreen mode Exit fullscreen mode

6.安装redis用于操作 Redis 的软件包:



npm install redis --save
npm install @types/redis --save-dev


Enter fullscreen mode Exit fullscreen mode

步骤 2:使用 Express.js 开发 Redis - 入门指南

在这一步中,我们将为 Express.js 应用程序搭建基本结构。

app.ts1. 在目录下创建一个名为以下名称的文件src



// src/app.ts

import express from 'express';

const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Hello Redis with Express.js and TypeScript!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});


Enter fullscreen mode Exit fullscreen mode

步骤 3:创建基本 Express 服务器

现在,让我们创建一个监听端口的基本 Express 服务器。

1.package.json在文件中添加启动脚本:



"scripts": {
  "start": "ts-node src/app.ts"
}


Enter fullscreen mode Exit fullscreen mode

2.启动服务器:



npm start


Enter fullscreen mode Exit fullscreen mode

您的 Express 服务器现在应该在http://localhost:3000运行,当您在 Web 浏览器中访问它时,应该会看到“Hello Redis with Express.js and TypeScript!”消息。

步骤 4:使用 Redis 缓存数据

在这一步中,我们将设置 Redis 并使用它来缓存 Express.js 应用程序中的数据。

1.安装该ioredis软件包,这是一个流行的Node.js Redis客户端:



npm install ioredis --save
npm install @types/ioredis --save-dev


Enter fullscreen mode Exit fullscreen mode

2.更新app.ts文件以包含 Redis 缓存:



// src/app.ts

import express from 'express';
import Redis from 'ioredis';

const app = express();
const port = process.env.PORT || 3000;

// Create a Redis client
const redis = new Redis();

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Hello Redis with Express.js and TypeScript!');
});

// Example of caching data
app.get('/cache', async (req, res) => {
  const cachedData = await redis.get('cachedData');

  if (cachedData) {
    // If data exists in the cache, return it
    res.send(JSON.parse(cachedData));
  } else {
    // If data is not in the cache, fetch it from the source
    const dataToCache = { message: 'Data to be cached' };
    await redis.set('cachedData', JSON.stringify(dataToCache), 'EX', 3600); // Cache for 1 hour
    res.send(dataToCache);
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});


Enter fullscreen mode Exit fullscreen mode

步骤 5:添加中间件以检查缓存中是否存在数据

为了改进我们的缓存机制,我们可以创建一个中间件函数,在访问路由处理程序之前检查缓存中是否存在数据。

1.添加以下中间件函数app.ts



// Middleware to check if data is in the cache
const checkCache = async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  const cachedData = await redis.get('cachedData');

  if (cachedData) {
    res.send(JSON.parse(cachedData));
  } else {
    next(); // Continue to the route handler if data is not in the cache
  }
};

// Use the checkCache middleware before the route handler
app.get('/cache', checkCache, async (req, res) => {
  const dataToCache = { message: 'Data to be cached' };
  await redis.set('cachedData', JSON.stringify(dataToCache), 'EX', 3600); // Cache for 1 hour
  res.send(dataToCache);
});


Enter fullscreen mode Exit fullscreen mode

现在,checkCache中间件会先检查缓存中是否存在数据,然后再执行路由处理程序。如果数据在缓存中,则会将其作为响应发送;否则,路由处理程序会获取数据并将其缓存。

步骤 6:Jest 测试

让我们来设置 Jest 来测试我们的 Express.js 应用程序。

1.安装 Jest 测试框架及相关软件包:



npm install jest @types/jest ts-jest supertest @types/supertest --save-dev


Enter fullscreen mode Exit fullscreen mode

tests2.在项目根目录下创建一个目录:



mkdir tests


Enter fullscreen mode Exit fullscreen mode

3. 为 Express.js 应用程序创建一个测试文件,例如app.test.ts



// tests/app.test.ts

import request from 'supertest';
import app from '../src/app';

describe('Express App', () => {
  it('responds with "Hello Redis with Express.js and TypeScript!" at the root URL', async () => {
    const response = await request(app).get('/');
    expect(response.status).toBe(200);
    expect(response.text).toBe('Hello Redis with Express.js and TypeScript!');
  });

  it('caches data when accessing the /cache route', async () => {
    const response1 = await request(app).get('/cache');
    expect(response1.status).toBe(200);

    const response2 = await request(app).get('/cache');
    expect(response2.status).toBe(200);
    expect(response2.body).toEqual(response1.body);
  });
});


Enter fullscreen mode Exit fullscreen mode

4.更新您的package.json代码,使其包含 Jest 测试脚本:



"scripts": {
  "start": "ts-node src/app.ts",
  "test": "jest",
  "test:watch": "jest --watch"
}


Enter fullscreen mode Exit fullscreen mode

5.运行 Jest 测试:



npm test


Enter fullscreen mode Exit fullscreen mode

步骤 7:API 测试(发送查询参数)

您可以通过发送查询参数来测试您的 API。

为此创建一个示例路由。

1.更新app.ts文件,添加一个接受查询参数的路由:



// src/app.ts

// ...

// Example route with query parameters
app.get('/api', (req, res) => {
  const { name } = req.query;
  res.send(`Hello, ${name || 'Guest'}!`);
});

// ...


Enter fullscreen mode Exit fullscreen mode

2.如果服务器尚未运行,请启动服务器:



npm start


Enter fullscreen mode Exit fullscreen mode

3.使用查询参数测试 API 路由:



curl "http://localhost:3000/api?name=Ruffiano"


Enter fullscreen mode Exit fullscreen mode

如果没有提供名称参数,您应该会看到以下响应:“你好,Ruffiano!”或“你好,访客!”。

结论

在本教程中,我们学习了如何使用 TypeScript 将 Redis 集成到 Express.js 应用程序中。我们涵盖了 Redis 缓存的设置、添加中间件以检查缓存、编写 Jest 测试以及测试 API 路由。您可以以此为基础,在 Express.js 项目中构建更复杂的、使用 Redis 缓存的应用程序。

文章来源:https://dev.to/ruffiano/using-redis-with-expressjs-typescript-31jn