>  기사  >  웹 프론트엔드  >  Node.js에서 Redis 데이터베이스를 읽고 쓰는 간단한 방법 application_node.js

Node.js에서 Redis 데이터베이스를 읽고 쓰는 간단한 방법 application_node.js

WBOY
WBOY원래의
2016-05-16 15:52:192295검색

이 기사를 시작하기 전에 Redis, Node.js 및 Node.js용 Redis 확장 프로그램을 설치했는지 확인하세요. - node_redis

먼저 새 폴더를 만들고 app.js라는 새 텍스트 파일을 만듭니다. 파일 내용은 다음과 같습니다.

var redis = require("redis")
  , client = redis.createClient();
 
client.on("error", function (err) {
  console.log("Error " + err);
});
 
client.on("connect", runSample);
 
function runSample() {
  // Set a value
  client.set("string key", "Hello World", function (err, reply) {
    console.log(reply.toString());
  });
  // Get a value
  client.get("string key", function (err, reply) {
    console.log(reply.toString());
  });
}

Redis에 연결되면 runSample 함수가 호출되어 값이 설정되고 해당 값을 읽어오게 됩니다.

OK
Hello World

EXIRE 명령을 사용하여 객체의 만료 시간을 설정할 수도 있습니다. 코드는 다음과 같습니다.

var redis = require('redis')
  , client = redis.createClient();
 
client.on('error', function (err) {
  console.log('Error ' + err);
});
 
client.on('connect', runSample);
 
function runSample() {
  // Set a value with an expiration
  client.set('string key', 'Hello World', redis.print);
  // Expire in 3 seconds
  client.expire('string key', 3);
 
  // This timer is only to demo the TTL
  // Runs every second until the timeout
  // occurs on the value
  var myTimer = setInterval(function() {
    client.get('string key', function (err, reply) {
      if(reply) {
        console.log('I live: ' + reply.toString());
      } else {
        clearTimeout(myTimer);
        console.log('I expired');
        client.quit();
      }
    });
  }, 1000);
}

참고: 위에 사용된 타이머는 단지 EXPIRE 명령을 보여주기 위한 것입니다. Node.js 프로젝트에서는 타이머를 주의해서 사용해야 합니다.

위 프로그램 실행 결과는 다음과 같습니다.


Reply: OK
I live: Hello World
I live: Hello World
I live: Hello World
I expired

다음으로 값이 만료되기 전에 지속되는 기간을 확인합니다.

var redis = require('redis')
  , client = redis.createClient();
 
client.on('error', function (err) {
  console.log('Error ' + err);
});
 
client.on('connect', runSample);
 
function runSample() {
  // Set a value
  client.set('string key', 'Hello World', redis.print);
  // Expire in 3 seconds
  client.expire('string key', 3);
 
  // This timer is only to demo the TTL
  // Runs every second until the timeout
  // occurs on the value
  var myTimer = setInterval(function() {
    client.get('string key', function (err, reply) {
      if(reply) {
        console.log('I live: ' + reply.toString());
        client.ttl('string key', writeTTL);
      } else {
        clearTimeout(myTimer);
        console.log('I expired');
        client.quit();
      }
    });
  }, 1000);
}
 
function writeTTL(err, data) {
  console.log('I live for this long yet: ' + data);
}

실행 결과:

Reply: OK
I live: Hello World
I live for this long yet: 2
I live: Hello World
I live for this long yet: 1
I live: Hello World
I live for this long yet: 0
I expired


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.