连接数据库配置文件—src/config/index.js
const REDIS = {host: '192.168.137.133',port: 15001,password: '123456'}export default {REDIS}
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 errorreturn 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 errorreturn new Error("Retry time exhausted");}if (options.attempt > 10) {// End reconnecting with built in errorreturn undefined;}// reconnect afterreturn 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)})}return}// const { promisify } = require("util");// const getAsync = promisify(client.get).bind(client);const getValue = (key) => {return client.getAsync(key)}const getHValue = (key) => {// v8 Promise method use util,must node > 8// return promisify(client.hgetall).bind(client)(key)// bluebrid asyncreturn 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,setValue,getValue,getHValue,delValue}
test.js
import { delValue, getHValue, getValue, setValue } from './RedisConfig'setValue('imooc', 'imooc message from redis client')getValue('imooc').then((res) => {console.log('getValue:' + res)}).catch((err) => {console.log('getValue,error:' + err)});delValue('imooc')setValue('imoocobj', {name: 'zbl',email: '95605355@qq.com',age: 30})getHValue('imoocobj').then((res) => {console.log('getHValue:' + JSON.stringify(res))})
