|
@@ -3,7 +3,7 @@ import redis from 'redis';
|
|
|
import nodeCache from 'node-cache';
|
|
|
import util from 'util';
|
|
|
import consola from 'consola/dist/consola';
|
|
|
-import config from '../config';
|
|
|
+import config from '@config';
|
|
|
|
|
|
// 是否使用redis
|
|
|
let isUseRedis: boolean = true
|
|
@@ -56,18 +56,19 @@ client.on('end', () => {
|
|
|
});
|
|
|
|
|
|
// redis查询和设置await/async化
|
|
|
-const promisify = util.promisify
|
|
|
-const getClient = promisify(client.get).bind(client);
|
|
|
-const setClient = promisify(client.set).bind(client);
|
|
|
-const setexClient = promisify(client.setex).bind(client);
|
|
|
+const promisify = util.promisify;
|
|
|
+const getClient = (key) => promisify(client.get).bind(client, key);
|
|
|
+const setClient = (key, value) => promisify(client.set).bind(client, key, value);
|
|
|
+const setexClient = (key, ttl, value) => promisify(client.setex).bind(client, key, ttl, value);
|
|
|
|
|
|
// 内存存储promise化,为了和redis使用方法保持一致
|
|
|
const getCache = (key: string): Promise<string|undefined> => {
|
|
|
+ console.log(key);
|
|
|
return new Promise(resolve => {
|
|
|
resolve(cache.get(key))
|
|
|
})
|
|
|
}
|
|
|
-const setCache = (key: string, value: string, ttl: number = 0): Promise<boolean> => {
|
|
|
+const setCache = (key: string, ttl: number = 0, value: string): Promise<boolean> => {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
const success = cache.set(key, value, ttl)
|
|
|
if (success) {
|
|
@@ -77,7 +78,7 @@ const setCache = (key: string, value: string, ttl: number = 0): Promise<boolean>
|
|
|
}
|
|
|
})
|
|
|
}
|
|
|
-const setexCache = (key: string, ttl: number, value: string, ) => setCache(key, value, ttl)
|
|
|
+const setexCache = (key: string, ttl: number, value: string, ) => setCache(key, ttl, value)
|
|
|
|
|
|
// 初始化测试
|
|
|
// client.setex('test', 30, '111111');
|
|
@@ -85,7 +86,7 @@ const setexCache = (key: string, ttl: number, value: string, ) => setCache(key,
|
|
|
|
|
|
export default () => {
|
|
|
return async (ctx, next) => {
|
|
|
- console.log(isUseRedis);
|
|
|
+ consola.info('redis is available:', isUseRedis);
|
|
|
if (isUseRedis) { // 如果redis连接失败,采用内存
|
|
|
ctx.$redis = { set: setClient, get: getClient, setex: setexClient };
|
|
|
} else {
|