一、安装

1. 安装Redis

http://www.feihu1996.cn/?id=109

2. 安装Node的Redis驱动

npm install redis
# 还可以安装更简约的hiredis库
npm install hiredis

二、基本功能

// 通过 Node 对 Redis 进行基础的 set 和 get 操作
const redis = require('redis'),
    client = redis.createClient()

client.on('error', (err)=>{
    console.log(err)
})

console.log('Setting key1')
client.set('key1', 'My String1', redis.print)

console.log('Getting key1')
client.get('key1', (err, reply)=>{
    console.log('Results for key1:')
    console.log(reply)
    client.end(true)
})

三、哈希表

// 哈希表是包含多个key的对象

const redis = require('redis')
    client = redis.createClient()

client.on('error', (err)=>{
    console.log(err)
})

console.log('Setting user hash')

// 每次设置一个 hash 值
client.hset('user', 'username', 'Angus Charles')
client.hset('user', 'firstname', 'angus')
client.hset('user', 'lastname', 'charles')

client.hkeys('user', (err, replies)=>{
    console.log('Results for user:')
    console.log(replies.length + ' replies:')
    replies.forEach((reply, i)=>{
        console.log(i + ': ' + reply)
    })
    client.end(true)
})
const redis = require('redis'),
    client = redis.createClient()

client.on('error', (err)=>{
    console.log(err)
})

console.log('Setting user hash')

// 同时设置多个 hash 值
client.hmset('user', 'username', 'Angus Charles', 'firstname', 'angus', 'lastname', 'charles')

client.hkeys('user', (err, replies)=>{
    console.log('Results for user')
    console.log(replies.length + ' replies:')
    replies.forEach((reply, i)=>{
        console.log(i + ' :' + reply)
    })
    client.end(true)
})
const redis = require('redis')
    client = redis.createClient()

client.on('error', (error)=>{
    console.log(error)
})

let user = {
    username: 'Angus Charles',
    firstname: 'angus',
    lastname: 'charles',
    email: 'gsx0312@qq.com',
    website: 'feihu1996.cn',
}

console.log('Setting user hash:')

//  使用对象来设置多个 hash 值
client.hmset('user', user)

client.hkeys('user', (err, replies)=>{
    console.log('Results for user')
    console.log(replies.length + ' replies:')
    replies.forEach((reply, i)=>{
        console.log(i + ' :' + reply)
    })
    client.end(true)
})

四、列表

const redis = require('redis'),
    client = redis.createClient()
    
client.on('error', (error)=>{
    console.log(error)
})

client.lpush('pendingusers', 'user0')
client.lpush('pendingusers', 'user1')
client.lpush('pendingusers', 'user2')
client.lpush('pendingusers', 'user3')

client.rpop('pendingusers', (error, username)=>{
    if(!error){
        console.log('Processing ' + username)
    }
    client.end(true)
})

五、集合

const redis = require('redis'),
    client = redis.createClient()

client.on('error', (error)=>{
    console.log(error)
})

client.sadd('myteam', 'member0')
client.sadd('myteam', 'member1')
client.sadd('myteam', 'member2')
client.sadd('myteam', 'member3')
client.sadd('myteam', 'member4')

client.smembers('myteam', (error, members)=>{
    console.log(members)
    client.end(true)
})

六、有序集合

const redis = require('redis'),
    client = redis.createClient()

client.on('error', (error)=>{
    console.log(error)
})

client.zadd('contestants', 60, 'member0')
client.zadd('contestants', 65, 'member1')
client.zadd('contestants', 26, 'member2')
client.zadd('contestants', 62, 'member3')
client.zadd('contestants', 24, 'member4')
client.zadd('contestants', 39, 'member5')
client.zadd('contestants', 26, 'member6')
client.zadd('contestants', 46, 'member7')
client.zadd('contestants', 63, 'member8')
client.zadd('contestants', 27, 'member9')
client.zadd('contestants', 27, 'member10')
client.zadd('contestants', 51, 'member11')
client.zadd('contestants', 41, 'member12')
client.zadd('contestants', 47, 'member13')
client.zadd('contestants', 40, 'member14')

client.zcard('contestants', (error, length)=>{
    if(!error){
        let contestantCount = length
        let membersPerTeam = Math.ceil(contestantCount / 3)
        client.zrange('contestants', membersPerTeam * 0, membersPerTeam * 1 - 1, (error, values)=>{
            if(error){
                console.log(error)
            }else{
                console.log('Young team: ' + values)
            }
        })
        client.zrange('contestants', membersPerTeam * 1, membersPerTeam * 2 - 1, (error, values)=>{
            if(error){
                console.log(error)
            }else{
                console.log('Middle team: ' + values)
            }            
        })
        client.zrange('contestants', membersPerTeam * 2, membersPerTeam * 3 - 1, (error, values)=>{
            if(error){
                console.log(error)
            }else{
                console.log('Elder team: ' + values)
                client.end(true)
            }            
        })
    }
})

七、发布 - 订阅(pub-sub)消息模型

//  Redis支持发布 - 订阅(pub-sub)消息模型
//  允许发送者(发布者)往频道里添加消息
//  然后由匿名的接收者(订阅者)使用

const redis = require('redis'),
    talkativeClient = redis.createClient(),
    pensiveClient = redis.createClient()

pensiveClient.on('subscribe', (channel, count)=>{
    talkativeClient.publish(channel, 'Welcome to ' + channel)
    talkativeClient.publish(channel, 'You subscribed to ' + count + ' channels!')
})

pensiveClient.on('unsubscribe', (channel, count)=>{
    if(0 === count){
        talkativeClient.end(true)
        pensiveClient.end(true)
    }
})

pensiveClient.on('message', (channel, message)=>{
    console.log(channel + ':' + message)
})

pensiveClient.on('ready', ()=>{
    pensiveClient.subscribe('quiet channel', 'peaceful channel', 'noisy channel')
    setTimeout(() => {
        pensiveClient.unsubscribe('quiet channel', 'peaceful channel', 'noisy channel')
    }, 1000)
})

八、Redis安全性

# Redis支持密码验证
#  要添加密码
#  需要编辑Redis的配置文件
requirepass your-password
const redis = require('redis'),
    client = redis.createClient()

//  auth命令必须在其他操作之前执行
//  客户端会保存密码
//  并且在重新连接的时候使用
//  Redis并没有提供用户管理功能
//  因为这会增加开销
client.auth('your-password')