Appearance
连接 redis
Redis client(support redis portocal) based on ioredis for egg framework
安装
bash
npm i egg-redis --save
1
配置
Change ${app_root}/config/plugin.js
to enable redis plugin:
javascript
exports.redis = {
enable: true,
package: "egg-redis",
};
1
2
3
4
5
2
3
4
5
Configure redis information in ${app_root}/config/config.default.js
:
Single Client
javascript
config.redis = {
client: {
port: 6379, // Redis port
host: "127.0.0.1", // Redis host
password: "auth",
db: 0,
},
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
使用方法
service
app/service/redis.js if(this.app.redis)
判断是否有启用 redis
javascript
"use strict";
const Service = require("egg").Service;
class RedisService extends Service {
async set(key, value, seconds) {
value = JSON.stringify(value);
if (this.app.redis) {
if (!seconds) {
await this.app.redis.set(key, value);
} else {
await this.app.redis.set(key, value, "EX", seconds);
}
}
}
async get(key) {
if (this.app.redis) {
const data = await this.app.redis.get(key);
if (!data) return;
return JSON.parse(data);
}
}
}
module.exports = RedisService;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
controller
app/controller/default/index.js 如果没有设置 redis 缓存,就去请求数据,再设置缓存
javascript
var topNav = await this.ctx.service.cache.get("index_topNav");
if (!topNav) {
topNav = await this.ctx.model.Nav.find({
position: 1,
});
await this.ctx.service.cache.set("index_topNav", topNav, 60 * 60);
}
1
2
3
4
5
6
7
2
3
4
5
6
7