redis
- 因为nodejs的redis模块3.0和4.0以上有差别
redis4.0代码
const redis = require('redis')
const redis_config = {
host: 'ip',
port: 'port',
password: 'password',
number: number,
}
const url = `redis://:${redis_config.password}@${redis_config.host}:${redis_config.port}/${redis_config.number}`
const redisClient = redis.createClient({'url': url})
redisClient.on('ready', () => {
console.log('redis is ready...')
})
redisClient.on('error', err => {
console.err(err)
})
async function fun(callback, key, value){
return new Promise(async (res, rej) => {
await redisClient.connect()
let ok = callback(key, value)
await redisClient.quit()
res(ok)
})
}
const db = {
async set(key, value){
return fun(async() => {
return await redisClient.set(key, value)
}, key, value)
},
async get(key){
return fun(async() => {
return await redisClient.get(key)
}, key)
},
async del(key){
return fun(async() => {
return await redisClient.del(key)
}, key)
},
}
async function runRedis(){
await db.set("key", "value")
console.log(await db.get("key"))
}
runRedis()
redis3.0代码
const config = {
port: port,
ip: 'host',
password: 'password'
}
const redis = require('redis')
const redisClient = redis.createClient(config.port, config.ip, {auth_pass: config.password})
redisClient.on('ready', () => {
console.log('redis is ready...')
})
redisClient.on('end', err => {
console.log('redis is quit...')
})
redisClient.on('error', err => {
console.error('err...', err)
})
const db = {
get: function(key){
return new Promise((res, rej) => {
redisClient.get(key, (err, value) => {
if(err) rej(err)
res(value)
})
})
},
set: function(key, value){
return new Promise((res, rej) => {
redisClient.set(key, value, (err, result) => {
if(err) rej(err)
res(result)
})
})
},
del: function(key){
return new Promise((res, rej) => {
redisClient.del(key, (err, result) => {
if(err) rej(err)
res(result)
})
})
}
}
const test = async function(){
console.log('setkey1: ', await db.set('key', 'value'))
console.log('getkey1: ', await db.get('key'))
console.log('delkey1: ', await db.del('key'))
console.log('getkey1: ', await db.get('key'))
console.log('delkey1: ', await db.del('key'))
redisClient.quit()
}
test()