[nodejs] noderedis配置以及set和get方法的封装

249 阅读1分钟
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") {
      // End reconnecting on a specific error and flush all commands with
      // a individual error
      return new Error("The server refused the connection");
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
      // End reconnecting after a specific timeout and flush all commands
      // with a individual error
      return new Error("Retry time exhausted");
    }
    if (options.attempt > 10) {
      // End reconnecting with built in error
      return undefined;
    }
    // reconnect after
    return Math.min(options.attempt * 100, 3000);
  },
})

client.on('error', (err) => {
  console.log('redis 链接发生异常..., 错误信息: ' + err)
})

// promiseify 
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
}