Swagger(现称OpenAPI)和Redis在Linux环境中可以很好地协同工作,主要通过以下几种方式:
description
字段记录各个API端点使用的Redis键模式和数据格式paths:
/users/{id}:
get:
summary: 获取用户信息
description: |
从Redis缓存获取用户信息,若不存在则查询数据库并缓存结果。
Redis键格式: user:{id}
缓存时间: 3600秒
parameters:
- name: id
in: path
required: true
schema:
type: integer
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const Redis = require('ioredis');
const YAML = require('yamljs');
const app = express();
const redis = new Redis({
host: 'localhost',
port: 6379
});
// 加载Swagger文档
const swaggerDocument = YAML.load('./api.yaml');
// API端点
app.get('/users/:id', async (req, res) => {
const { id } = req.params;
const cacheKey = `user:${id}`;
try {
// 尝试从Redis获取缓存
const cachedUser = await redis.get(cacheKey);
if (cachedUser) {
return res.json(JSON.parse(cachedUser));
}
// 无缓存则从数据库获取
const user = await db.getUser(id);
// 设置缓存
await redis.set(cacheKey, JSON.stringify(user), 'EX', 3600);
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 设置Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
// 从Redis加载Swagger文档
async function loadSwaggerDoc() {
const doc = await redis.get('swagger:doc');
return doc ? JSON.parse(doc) : {};
}
// 更新Swagger文档
async function updateSwaggerDoc(path, method, docPart) {
const currentDoc = await loadSwaggerDoc();
currentDoc.paths = currentDoc.paths || {};
currentDoc.paths[path] = currentDoc.paths[path] || {};
currentDoc.paths[path][method] = docPart;
await redis.set('swagger:doc', JSON.stringify(currentDoc));
}
paths:
/api/resource:
get:
summary: 获取资源
description: |
限流策略: 每个IP每分钟最多60次请求
Redis键格式: rate_limit:{ip}:{timestamp}
responses:
200:
description: 成功
429:
description: 请求过多
Redis配置:
sudo systemctl status redis
/etc/redis/redis.conf
中调整maxmemory
和相关策略Swagger文档生成:
swagger-jsdoc
自动从代码注释生成文档监控:
redis-cli info stats | grep keyspace
安全:
通过以上方式,Swagger和Redis可以在Linux环境中有效协同,既提供了清晰的API文档,又利用Redis提升了API性能。