一、get&set方法 && 哈希表hset&hgetall && BlueBird
/src/config/index.js
const DB_URL = 'mongodb://test:123456@203.195.161.212:15001/testdb'const REDIS = { host: '203.195.161.212', port: 15001, password: '123456'}export default { DB_URL, REDIS}
/src/config/RedisConfig.js
import redis from 'redis'import { promisifyAll } from 'bluebird'import config from './index'const options = { host: config.REDIS.host, port: config.REDIS.port, password: config.REDIS.password, 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); }}// const client = redis.createClient(options)const client = promisifyAll(redis.createClient(options))client.on('error', err => { console.log(`Redis Client Error:${err}`)})const setValue = (key, value) => { if (typeof value === 'undefined' || value === null || value === '') { return } if (typeof value === 'string') { client.set(key, value) } else if (typeof value === 'object') { Object.keys(value).forEach(item => { client.hset(key, item, value[item], redis.print) //redis.print返回日志信息 }) }}// const { promisify } = require("util");// const getAsync = promisify(client.get).bind(client);const getValue = (key) => { return client.getAsync(key)}const getHValue = (key) => { // v8 Promisify method use util, must node > 8 // return promisify(client.hgetall).bind(client)(key) // hgetall转成promise方法 @return function // bluebird async return client.hgetallAsync(key)}const delValue = (key) => { client.del(key, (err, res) => { if (res === 1) { console.log('delete successfully') } else { console.log(`delete redis key error:${err}`) } })}export { client, getValue, setValue, getHValue, delValue}
/src/config/test.js
import {getHValue, getValue, setValue, delValue} from "./RedisConfig"setValue('sampson', 'sampson message from redis client')getValue('sampson').then(res => { console.log(`getValue:${res}`)})delValue('sampson')setValue('sampsonobj', {name: 'sampson', age: 30, email: '419582275@qq.com'})getHValue('sampsonobj').then((res) => { console.log(`getHValue:${JSON.stringify(res, null, 2)}`)})
redis资料参考