和连接 SQLite 一样,这里也使用单例模式和引入模块的方式让 Express 使用 Redis
ioredis
单例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const ioredis = require("ioredis"); class Redis { constructor(options) { if (this.instance) { return this.instance; } this.instance = Redis.init(options); return this.instance; }
static init(options = {}) { if (this.instance) { return this.instance; } this.instance = new ioredis(options); return this.instance; } } module.exports = Redis;
|
使用
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 27 28 29
| const express = require("express"); const router = express.Router();
const redis = require("../../db/redis").init();
const { login } = require("../../joi/v1/auth.joi");
const { errcode } = require("../../../utils/index");
router.delete("", async (req, res, next) => { try { const decodeToken = req.decodeToken; await redis.del(`${decodeToken.id}#refresh_token`); await redis.del(`${decodeToken.id}#access_token`); const { status, body } = errcode(0); res.status(status).send(body); } catch (error) { next(error); } });
module.exports = router;
|