zoukankan      html  css  js  c++  java
  • [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 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);
          });
        }
      });
    });
  • 相关阅读:
    Java读书笔记
    b_aw_旅游计划(树的中心变形)
    b_lc_秋叶收集器(分类讨论dp+滚动数组优化)
    b_lg_涂色(从小区间做起,讨论s[l]和s[r]的关系)
    c_lc_早餐组合(排序+双指针)
    c_aw_鱼塘钓鱼(大根堆)
    b_pat_栈(2*multiset+stack)
    c_pat_推荐系统(set模拟)
    b_lg_时态同步(后序遍历统计每棵子树的最大高度)
    b_lc_统计不开心的朋友(预处理+模拟)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4148525.html
Copyright © 2011-2022 走看看