LoginSignup
23
24

More than 5 years have passed since last update.

node-redisを入れてみるメモ

Last updated at Posted at 2012-09-04

こないだ作ったmongoのレプリカセット( http://qiita.com/items/b5e99bf4923b84b2bb40 )が安定して仕事してくれてるぽいので、次は、欲を出して別のDBで「キーと値の対を、すべてメモリ上に保存する超高速な」redisのクラスタもテストしてみたくなる。

思い立ったが台湾吉日(注1)。牛久大仏の青銅鋳造は@台湾謹製、船で運びました。ってことで(<関係ない^^?)、何はともあれ、さっそく、やってみる。

で、nodeで使えるredisはすでにいっぱいあるけれど、一番人気ありそうなnode-redis。
https://github.com/mranney/node_redis

思い立ったが台湾吉日

注1:「思い立ったが台湾吉日」2012年 台湾観光局の日本向け観光スローガン

インストール

npm install redis

おしまい。でも、これはクライアントなので、サーバーが必要。

redis-serverのインストール

redisの入手/インストール方法もいろいろあって、、、

wget http://redis.googlecode.com/files/redis-バージョン.tar.gz
git clone git://github.com/antirez/redis.git

などもありますが、うちはUbuntuなのでこれでいきます。

sudo apt-get install redis-server

これだけ。

redis-serverのインストール完了

apt-getでやると redis.confは/etc/redis/redis.confに作られてて、最初から daemonize yesになってて、timeout は 300、logfileは /var/log/redis/redis-server.log ということになってました。portはデフォルトの6379、bindは'127.0.0.1'に固定です。

スタート・ストップ・再起動はこんな感じで行けます。

sudo /etc/init.d/redis-server start | stop | restart

node-redisから使ってみる

さて、redisサーバーが立ち上がったので、node-redisで確認します
まぁ、gitにあるサンプルやってみるです。

test.js
    var redis = require("redis"),
        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();
    });

    client.set("test", "うひょー");

    client.get("test", function(err, data){
      console.log(data);

    });

結果

キー/バリューなのでとても簡単す。

node test.js
Reply: OK
Reply: 0
Reply: 0
2 replies:
    0: hashtest 1
    1: hashtest 2
うひょー

今日は、別のマシンからのレプリケーションも試したので、あとでそっちも忘れないようにメモしておきます( redisにレプリケーションを設定する http://qiita.com/items/7f97870ef06df9257fd4 )。これも超簡単^^ うれしい時代になってきました。

参考

redisドキュメント日本語訳
http://redis.shibu.jp/index.html
Redis Command Reference
http://redis.io/commands

23
24
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
24