원문 링크 - http://www.catonmat.net/blog/nodejs-modules-redis/

본 문서는 저자의 허락을 얻어 해당 포스팅을 번역한 것입니다.

1회 연재 - dnode (RPC 라이브러리)

2회 연재 - optimist (옵션 파서)

3회 연재 - lazy (lazy 리스트 처리)

4회 연재 - request (HTTP 스트림 처리)

5회 연재 - hashish (해시 처리)

6회 연재 - read (쉬운 표준 입력 처리)

7회 연재 - ntwitter (트위터 API)

8회 연재 - socket.io (웹소켓 통신)

오늘은 최고의 node.js Redis 클라이언트 API 라이브러리인 node_redis 모듈을 소개할 것이다. 이러한 Redis node.js 모듈은 Matt Ranney에 의해 작성됐다.

node_redis는 완벽한 node.js용 Redis 클라이언트 라이브러리다. 이 라이브러리는 실험적인 Redis 서버 브랜치에 추가된 EVAL과 같은 많은 명령어들을 포함하여 모든 Redis 명령어들을 지원한다.

다음은 redis 라이브러리 이용한 예제이다.

var redis = require("redis");
var client = redis.createClient();

client.on("error", function (err) {
    console.log("Error " + err);
});

client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
    console.log(replies.length + " replies:");
    replies.forEach(function (reply, i) {
        console.log(" " + i + ": " + reply);
    });
    client.quit();
});

위 예제를 실행했을 때의 결과는 다음과 같다.

mjr:~/work/node_redis (master)$ node example.js
Reply: OK
Reply: 0
Reply: 0
2 replies:
    0: hashtest 1
    1: hashtest 2
mjr:~/work/node_redis (master)$

각각의 Redis 명령어는 client 객체의 함수로 제공된다. 이러한 모든 함수들은 args 배열 인자에 선택적으로 callback 함수 인자를 받거나, 여러 개의 각가의 인자들과 그 뒤에 선택적인 콜백 함수를 선택적인 인자로 넘겨받는다.

다음은 배열 인자와 콜백 함수를 넘겨받는 함수 예제이다.

client.mset(["key 1", "val 1"], function (err, res) {});

다음은 위 함수 호출과 동일하나, 앞에서 설명한 두번째 스타일 (각각의 인자들과 콜백 함수를 넘기는 형식)로 작성한 코드다.

client.mset("key 1", "val 1", function (err, res) {});

위 두 가지 함수 호출 방법 모두 콜백 함수 인자는 옵션이라는 것을 기억해라. 다음 예제는 콜백 함수가 없는 함수 호출을 보여준다.

client.set("some key", "some val");
client.set(["some other key", "some val"]);

Redis 명령어를 확인하기 위해서는 Redis 명령어 레퍼런스 사이트를 참조해라.

명령어 함수들은 편의를 위해 소문자나 대문자 형식으로 호출할 수 있다. 가령 client.get()client.GET() 는 동일하다.

npm을 통해 redis 모듈을 설치할 수 있다.

npm install redis

Redis의 GitHub 사이트: https://github.com/mranney/node_redis.

Pieter Noordhuis는 공식적인 hiredis C 라이브러리를 바인딩한 넌블럭킹이면서 빠른 모듈을 개발하고 있다. 그것은 hiredis-node 모듈이다. hiredis 모듈을 사용하기 위해서는, 다음과 같이 npm 명령을 실행해라.

npm install hiredis redis

만약 hiredis가 설치되어 있다면, node_redis는 디폴트로 그것을 이용할 것이다. 그렇지 않으면, 순수 자바스크립트 파서가 사용될 것이다.

Enjoy!

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!