[Node.js] Level 7. Persisting Data
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 questions
key.
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 redis
to 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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [Node.js] Level 5. Express
Express Routes Let's create an express route that accepts GET requests on'/tweets' and responds by s ...
- [Node.js] Level 2 new. Event
Chat Emitter We're going to create a custom chat EventEmitter. Create a new EventEmitter object and ...
- 了不起的Node.js读书笔记
原文摘自我的前端博客,欢迎大家来访问 http://www.hacke2.cn 第二章 Js概览 基于GoogleV8引擎 Object.keys(o) 数组方法:遍历forEach.过滤filter ...
- Node.js内置的文件系统模块(fs)
异步读取文件 按照js的标准,异步读取一个文本文件的格式如下: 'use strict' const fs = require('fs') fs.readFile('test.txt', 'utf-8 ...
- Node.js开发者最常范的10个错误
目录 前言 1 不使用开发工具 1.1 自动重启工具 1.2 浏览器自动刷新工具 2 阻塞event loop 3 频繁调用回调函数 4 圣诞树结构的回调(回调的地狱) 5 创建一个大而完整的应用程序 ...
- Node.js的线程和进程
http://www.admin10000.com/document/4196.html 前言 很多Node.js初学者都会有这样的疑惑,Node.js到底是单线程的还是多线程的?通过本章的学习,能够 ...
随机推荐
- 字节顺序重置及“#include <algorith.h>”相关的STL最重要的头文件提醒
这两天在写一个程序,需要将二进制文件中的数据以指定结构读入内存,说明文档中有提到大端序和小端序(Big Endian or Little Endian) 的概念,就找了一下字节顺序重置的算法,在一篇名 ...
- DOM笔记(七):开发JQuery插件
在上一篇笔记本中,讲解了如何利用jQuery扩展全局函数和对象:DOM笔记(六):怎么进行JQuery扩展? 在这篇笔记本中,将开发一个简单的动画插件,名称是example-plugin,用其实现一个 ...
- select多个字段赋值给多个变量
在存储过程中定义了变量v1 int;v2 int;v3 int;从表tab1选择3个字段f1,f2,f3赋值给这三个变量,要如何写 如果单个变量可以 select f1 into v1 from t ...
- kali install fcitx
1 卸载fcitx相关软件包 如果系统安装了fcitx相关东西,需要卸载,因为源的fcitx版本太低.请谨慎,后果自负. apt-get purge fcitx-* 2 手动下载最新的fcitx软件包 ...
- 性能测试-ApacheBench
基本简介 ApacheBench 是一个指令列程式,专门用来执行网站服务器的运行效能,特别是针对Apache 网站服务器.这原本是用来检测 Apache 网站服务器能够提供的效能,特别是可以看出Apa ...
- EF selection expression 与 Linq备忘
一.左连接查询 var query = people.GroupJoin(pets, person => person, pet => pet.Owner, (person, petCol ...
- 搭建sql注入实验环境(基于windows)
搭建服务器环境 1.下载xampp包 地址:http://www.apachefriends.org/zh_cn/xampp.html 很多人觉得安装服务器是件不容易的事,特别是要想添加MySql, ...
- 关于网站编码显示问题 效果是 访问 带有中文注释的sass文件出现编码报错。
首先查看环境变量 export declare -x HOME="/home/piperck" declare -x LANG="en_US.UTF-8" de ...
- ASP.NET的分页方法(二)
第二讲主要使用到了常用的分页控件aspnetpager,这里对他就行一个简单的应用,具体大家可以到杨涛的博客上去寻找相关的DLL, 首先要先引用AspNetPager.dll,然后把这个DLL同时添加 ...
- HDU4289Control(最大流)
看了这道题,然后重新开始练习自己的刚敲不久的网络流,发现还是难以一遍敲得完整啊,,,,, 调了...遍,改了...遍,测了...遍,交了,,,遍,总算是A了,,不简单啊 然后试着用了其他两种算法EK和 ...