学堂 学堂 学堂公众号手机端

Node.js封装redis操作及代码是什么

lewis 1年前 (2024-04-05) 阅读数 5 #技术
今天这篇我们来学习和了解“Node.js封装redis操作及代码是什么”,下文的讲解详细,步骤过程清晰,对大家进一步学习和理解“Node.js封装redis操作及代码是什么”有一定的帮助。有这方面学习需要的朋友就继续往下看吧!



配置文件: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)
})


到此这篇关于“Node.js封装redis操作及代码是什么”的文章就介绍到这了,更多相关Node.js封装redis操作及代码是什么内容,欢迎关注博信技术资讯频道,小编将为大家输出更多高质量的实用文章!
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门