Simple Redis Commands

Let's start practicing using the redis key-value store from our node application.

Require the redis module and assign it to a variable called redis.

var redis = require('redis');

Create a redis client and assign it to a variable called client.

var client = redis.createClient()

On the client, set the name property to your name.

client.set('name', 'Answer');
var redis = require('redis'),
client = redis.createClient(); client.set('name', 'Answer');

Get A Key

We have already stored a value in the question key. Use the redis client to issue a get command to redis to retrieve and then log the value.

Use the redis client to issue a get command using the 'question' key to retrieve a value. Remember, the get function takes a callback which expects two arguments, error and data.

Log the value retrieved with console.log.

var redis = require('redis');
var client = redis.createClient(); client.get('question', function(err, data){
console.log(data);
});

Working With Lists 1

As we saw in the video, redis can do more than just simple key-value pairs. We are going to be using redis' LISTS later to add persistence to our live-moderation app, so let's practice using them now

Using the redis client's lpush command, insert question1 into thequestions list. Then, console.log the result you receive. Remember, thelpush function takes a callback as its last argument, which expects anderror and value to be passed as arguments.

client.lpush('questions', question1, function(err, data){
console.log(data);
});

Using the redis client's lpush command, insert question2 into the questions list. Then console.log the result you receive.

var redis = require('redis');
var client = redis.createClient(); var question1 = "Where is the dog?";
var question2 = "Where is the cat?"; client.lpush('questions', question1, function(err, data){
console.log(data);
}); client.lpush('questions', question2, function(err, data){
console.log(data);
});

Working With Lists 2

Now that we have seeded the questions list, use the lrange()command to return all of the items and log them.

Use the lrange() command to return all of the items from the questionskey.

Now that we have called lrange(), use console.log to log the result from redis.

var redis = require('redis');
var client = redis.createClient(); client.lrange('questions', 0, -1, function(err, data){
console.log(data);
});

Persisting Questions

Let's go back to our live-moderation app and add some persistence, first to the questions people ask.

Use the lpush command to add new questions to the list namedquestions. Do this inside the listener for the 'question' event.

redisClient.lpush('questions', question);
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socket = require('socket.io');
var io = socket.listen(server); var redis = require('redis');
var redisClient = redis.createClient(); io.sockets.on('connection', function(client) {
client.on('answer', function(question, answer) {
client.broadcast.emit('answer', question, answer);
}); client.on('question', function(question) {
if(!client.question_asked) {
client.question_asked = true;
client.broadcast.emit('question', question);
// add the question to the list here
redisClient.lpush('questions', question);
}
});
});

Emitting Stored Questions

Now that we have questions stored in redis, let's emit them whenever a new client connects to the server through socket.io.

Use the lrange command to retrieve a list of questions that represent thequestions list within redis.

Inside of the lrange callback, use a forEach loop to iterate through thequestions and emit() each question to the client. Remember, don't usebroadcast.emit because we only want to send the questions to the client that is connecting to the server.

  redisClient.lrange('questions', 0, -1, function(err, questions){
questions.forEach(function(question){
client.emit("question", question);
});
});
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server); var redis = require('redis');
var redisClient = redis.createClient(); io.sockets.on('connection', function(client) {
redisClient.lrange('questions', 0, -1, function(err, questions){
questions.forEach(function(question){
client.emit("question", question);
});
});
client.on('answer', function(question, answer) {
client.broadcast.emit('answer', question, answer);
}); client.on('question', function(question) {
if(!client.question_asked) {
client.question_asked = true;
client.broadcast.emit('question', question);
redisClient.lpush("questions", question);
}
});
});

Limiting Questions Stored

Great work! One last thing though, since every time a new question comes in we store it in the questions list, we might run into a problem where there are just too many questions stored in that list.

Add a callback to lpush that will be used to limit the size of the list down to a max of 20.

Use the ltrim command to limit the size of the list stored within redisto a maximum size of 20.

      redisClient.lpush("questions", question, function(){
redisClient.ltrim("questions", 0, 19);
});
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server); var redis = require('redis');
var redisClient = redis.createClient(); io.sockets.on('connection', function(client) { redisClient.lrange('questions', 0, -1, function(err, messages){
messages.forEach(function(m){
client.emit('question', m);
});
}); client.on('answer', function(question, answer) {
client.broadcast.emit('answer', question, answer);
}); client.on('question', function(question) {
if(!client.question_asked) {
client.question_asked = true;
client.broadcast.emit('question', question);
redisClient.lpush("questions", question, function(){
redisClient.ltrim('questions', 0, 19);
});
}
});
});

[Node.js] Level 7. Persisting Data的更多相关文章

  1. [Node.js] Provide req.locals data though middleware

    We can create Template Helpers, which can contains some common reuseable data and libs. /* This is a ...

  2. [Node.js] Level 6. Socket.io

    6.2 Setting Up socket.io Server-Side So far we've created an Express server. Now we want to start bu ...

  3. [Node.js] Level 3 new. Steam

    File Read Stream Lets use the fs module to read a file and log its contents to the console. Use the  ...

  4. [Node.js] Level 5. Express

    Express Routes Let's create an express route that accepts GET requests on'/tweets' and responds by s ...

  5. [Node.js] Level 2 new. Event

    Chat Emitter We're going to create a custom chat EventEmitter. Create a new EventEmitter object and ...

  6. 了不起的Node.js读书笔记

    原文摘自我的前端博客,欢迎大家来访问 http://www.hacke2.cn 第二章 Js概览 基于GoogleV8引擎 Object.keys(o) 数组方法:遍历forEach.过滤filter ...

  7. Node.js内置的文件系统模块(fs)

    异步读取文件 按照js的标准,异步读取一个文本文件的格式如下: 'use strict' const fs = require('fs') fs.readFile('test.txt', 'utf-8 ...

  8. Node.js开发者最常范的10个错误

    目录 前言 1 不使用开发工具 1.1 自动重启工具 1.2 浏览器自动刷新工具 2 阻塞event loop 3 频繁调用回调函数 4 圣诞树结构的回调(回调的地狱) 5 创建一个大而完整的应用程序 ...

  9. Node.js的线程和进程

    http://www.admin10000.com/document/4196.html 前言 很多Node.js初学者都会有这样的疑惑,Node.js到底是单线程的还是多线程的?通过本章的学习,能够 ...

随机推荐

  1. 使用源码编译wxpython-基于python2.7

    1.前言 本文主要讲述在linux环境下进行编译wxpython,在windows下面安装wxpython很简单,只要下载,然后直接执行exe文件,下一步下一步即可安装,在linux下面,则具有很多步 ...

  2. 简易nagios安装出现的问题及解决方法

    安装时候所遇到的问题: A 安装PHP的时候报错xml2-config未找到 安装PHP的时候报错:未找到包libxml2 解决方法:安装libxml2包即可,libxml2是php的依赖包,从而需要 ...

  3. 【LeetCode】58 - Length of Last Word

    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...

  4. 闭包在python中的应用,translate和maketrans方法详解

    python对字符串的处理是比较高效的,方法很多.maketrans和translate两个方法被应用的很多,但是具体怎么用常常想不起来. 让我们先回顾下这两个方法吧: 1.s.translate(t ...

  5. effective c++:dynamic_cast,避免返回handles指向对象内部

    关于dynamic_cast 假定我们有一个基类指针bp,我们在运行时需要把它转换成他的派生类指针,这个时候需要用到dynamic_cast. Derived *dp = dynamic_cast&l ...

  6. Canvas 2D绘制抗锯齿的1px线条

    当绘制1像素的线条时,发现多条线明显存在着粗细不均的问题,线条带有明显的锯齿. 事实上,Canvas的绘制线条指令都存在这个状况,如lineTo,arcTo,strokeRect. 解决方案是将Can ...

  7. Tilera 服务器上hadoop单机版测试

    ---恢复内容开始--- 本篇博客用来记录在单个Tilera服务器上安装hadoop并且测试的经历,参阅了大多数博客. 1.Tilera服务器介绍 本Tilera服务器配备9核CPU,共挂在6块硬盘, ...

  8. hive权威安装出现的不解错误!(完美解决)两种方法都可以

    以下两种方法都可以,推荐用方法一! 方法一: 步骤一: yum -y install mysql-server 步骤二:service mysqld start 步骤三:mysql -u root - ...

  9. invoking gdb

    [invoking gdb] The most usual way to start gdb is with one argument, specifying an executable progra ...

  10. GWT工程架构分析与理解

    上一篇文章中介绍了GWT技术的一些理论性的东西,涉及到GWT得一些技术原理及实现.接下来笔者将通过创建一个GWT工程去理解分析GWT工程架构.     GWT工程架构解析 笔者使用的是Eclipse插 ...