Egg.js 集成 Redis 插件 egg-redis
教程
egg-redisredis plugin for egg项目地址:https://gitcode.com/gh_mirrors/eg/egg-redis
1. 项目介绍
egg-redis
是一个用于 Egg.js 框架的 Redis 客户端插件,它利用了高性能的 ioredis 库来提供与 Redis 服务器的连接。该插件支持单客户端模式、多客户端模式以及 Redis Sentinel 高可用配置。通过简单的配置,你可以在你的 Egg.js 应用中轻松地集成 Redis 缓存和数据存储功能。
2. 项目快速启动
安装依赖
在你的项目目录中,执行以下命令安装 egg-redis
:
npm install egg-redis --save
或
yarn add egg-redis --save
配置插件
在 config/plugins.js
文件中启用 egg-redis
插件:
exports.redis = {
enable: true,
package: 'egg-redis',
};
配置 Redis 连接
在 config/config.default.js
或相应环境的配置文件(如 config/config.local.js
)中添加 Redis 配置:
config.redis = {
client: {
port: 6379, // Redis 端口
host: '127.0.0.1', // Redis 主机地址
password: 'auth', // Redis 密码(如果有的话)
db: 0, // 数据库索引
},
};
使用示例
在你的服务中注入 Redis 客户端:
// {app_root}/app/service/user.js
const { Service } = require('egg');
class UserService extends Service {
async saveUser() {
const redis = this.app.redis;
await redis.set('user', 'John Doe');
const user = await redis.get('user');
return user;
}
}
module.exports = UserService;
3. 应用案例与最佳实践
LRU 本地缓存
你可以结合 lru-cache
来实现本地缓存策略:
const lru = require('lru-cache');
// ...
class UserService extends Service {
constructor(ctx) {
super(ctx);
this.cache = lru({
max: 1000,
length: n => n.length,
dispose(key, value) {},
maxAge: 1000 * 60 * 5, // 缓存有效期5分钟
});
}
async getUser(key) {
const cached = this.cache.get(key);
if (cached) return cached;
const user = await this.app.redis.get(key);
this.cache.set(key, user);
return user;
}
}
事务操作
ioredis 支持 Redis 事务,你可以在需要时使用 multi
和 exec
方法:
async batchOperation() {
const multi = this.app.redis.multi();
multi.incr('counter');
multi.set('key', 'value');
const results = await multi.exec();
console.log(results);
}
4. 典型生态项目
- Egg.js:作为微服务架构的基础框架,提供了丰富的插件机制。
- ioredis:
egg-redis
的底层实现,强大的 Redis 客户端库。 - Lodash: 可用于辅助数据处理和对象操作,提高代码效率。
使用 egg-redis
插件,可以结合上述生态项目构建高可用、性能优越的服务。更多关于 egg-redis
的配置和使用方法,可以参考其官方文档:https://github.com/eggjs/egg-redis。
egg-redisredis plugin for egg项目地址:https://gitcode.com/gh_mirrors/eg/egg-redis
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考