import Redis from 'redis'
import {promisify} from 'util'
const client = Redis.createClient({
host: 'localhost',
port: 6379,
detect_buffers: true,
retry_strategy: function(options) {
if (options.error && options.error.code === "ECONNREFUSED") {
return new Error("The server refused the connection");
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error("Retry time exhausted");
}
if (options.attempt > 10) {
return undefined;
}
return Math.min(options.attempt * 100, 3000);
},
})
client.on('error', (err) => {
console.log('redis 链接发生异常..., 错误信息: ' + err)
})
const getAsync = promisify(client.get).bind(client)
const getValue = (key) => {
return getAsync(key)
}
const getHValueAsync = (key) => {
return promisify(client.hgetall).bind(client)(key)
}
const setValue = (key, value, timeout) => {
if (typeof value === 'undefined' || typeof value == null || typeof value === '') {
return
} else if (typeof value === 'string') {
client.set(key, value)
client.expire(key, timeout)
} else if(typeof value === 'object') {
Object.keys(value).forEach(item => {
client.hset(key, item, value[item], Redis.print)
client.expire(key, timeout)
})
}
}
export {
client,
getValue,
setValue,
getHValueAsync
}