使用nodeJs操作redis - 封装promise

配置文件:RedisOptions.js
const options = {
  host: '208.167.233.104',
  port: 15001,
  password: '123456',
  detect_buffers: true // 传入buffer 返回也是buffer 否则会转换成String
}
 
module.exports = options
 
封装redis操作:RedisConfig.js 需要安装redis的npm包 (3.0.2)
const redis = require('redis')
const redisOptions = require('./RedisOptions')
 
const options = {
  host: redisOptions.host,
  port: redisOptions.port,
  password: redisOptions.password,
  detect_buffers: redisOptions.detect_buffers, // 传入buffer 返回也是buffer 否则会转换成String
  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);
  }
}
 
// 生成redis的client
const client = redis.createClient(options)
 
// 存储值
const setValue = (key, value) => {
  if (typeof value === 'string') {
    client.set(key, value)
  } else if (typeof value === 'object') {
    for (let item in value) {
      client.hmset(key, item, value[item],redis.print)
    }
  }
}
 
// 获取string
const getValue = (key) => {
  return new Promise((resolve, reject) => {
    client.get(key, (err, res) => {
      if (err) {
        reject(err)
      }else{
        resolve(res)
      }
    })
  })
}
 
// 获取hash
const getHValue = (key) => {
  return new Promise((resolve, reject) => {
    client.hgetall(key, function (err, value) {
      if (err) {
        reject(err)
      } else {
        resolve(value)
      }
    })
  })
}
 
// 导出
module.exports = {
  setValue,
  getValue,
  getHValue
} 
 
使用:test.js
const redis = require('./RedisConfig')
 
redis.setValue('student', {
  name: 'xiaoming',
  age: 18,
  sex: 1
})
 
redis.setValue('book', 'yuwen')
 
redis.getValue('book').then(res => {
  console.log(res)
}).catch(err => {
  throw new Error(err)
})
 
redis.getHValue('student').then(res => {
  console.log(res)
}).catch(err => {
  throw new Error(err)
})

 

posted @ 2020-04-07 11:17  博客小鹏鹏  阅读(2566)  评论(0编辑  收藏  举报