debug-server-next
Version:
Dev server for hippy-core.
86 lines (85 loc) • 2.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisModel = void 0;
const tslib_1 = require("tslib");
const redis_1 = require("redis");
const config_1 = require("@/config");
const log_1 = require("@/utils/log");
const base_model_1 = require("../base-model");
const log = new log_1.Logger('redis-model');
/**
* 封装 redis 的增删查改接口(注:value 统一存储为 hashmap 格式)
* 线上环境多机部署时用此模型
*/
class RedisModel extends base_model_1.DBModel {
constructor() {
super();
if (!this.client) {
this.client = createMyClient();
}
}
static getInstance() {
if (!RedisModel.instance) {
RedisModel.instance = new RedisModel();
}
return RedisModel.instance;
}
/**
* 初始化数据库连接
*/
init() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
// ⚠️ Publisher, Subscriber 必须 connect 之后再开始发布订阅,否则会先进入 PubSub mode,不能发送 AUTH 命令
yield this.client.connect();
}
catch (e) {
log.error('connect redis failed: %s', e.stack);
}
});
}
/**
* 查询 hashmap 的所有 value
*/
getAll(key) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const hashmap = yield this.client.hGetAll(key);
return Object.values(hashmap)
.map((item) => {
let itemObj;
try {
itemObj = JSON.parse(item);
}
catch (e) {
log.error('parse redis hashmap fail, key: %s', item);
}
return itemObj;
})
.filter((v) => v);
});
}
upsert(key, field, value) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
let strValue = value;
if (typeof value !== 'string')
strValue = JSON.stringify(value);
return this.client.hSet(key, field, strValue);
});
}
delete(key, field) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return this.client.hDel(key, field);
});
}
}
exports.RedisModel = RedisModel;
const createMyClient = () => {
const client = redis_1.createClient({ url: config_1.config.redis.url });
client.on('error', (e) => {
log.error('create redis client error: %s', e === null || e === void 0 ? void 0 : e.stack);
});
client.on('connect', log.error.bind(log));
client.on('warning', log.error.bind(log));
client.on('ready', log.error.bind(log));
return client;
};