node.js redis clusterに接続する

Javascript

node_redisは現時点ではredis clusterに対応していないので、redis clusterに対応しているライブラリを探してみたところ、ioredisが一番githubのスターが多いようなので、ioredisを使うことにしました。

https://github.com/luin/ioredis

導入

 $ npm install ioredis

redis clusterに接続するには下記のように、コンストラクターでclusterを構成するノードを列挙します。

 var Redis = require('ioredis');
 
 var cluster = new Redis.Cluster([{
   port: 6380,
   host: '127.0.0.1'
 }, {
   port: 6381,
   host: '127.0.0.1'
 }]);
 
 cluster.set('foo', 'bar');
 cluster.get('foo', function (err, res) {
   // res === 'bar'
 });

node command not found

Linuxサーバー

node command not found

種を明かすとバカバカしい話なのですが、また同じことをするかもしれないので、書いておきます。

sudoでルート化して、

 # node

とすると

 -bash: node: command not found

となってしまいました。

あれれ?nodeってインストールされてなかったっけ?
と思い、インストールされているか調べたりしていましたが、su – で本当の管理者権限でnodeを動作させたら動作できました。

 /root/node

においてあったので、sudoじゃダメだった、ということですね(^_^;

node.js

node.js インストール

node.jsとは

Google V8ベースのイベントI/O Webアプリケーションフレームワークです。
リアルタイムでハイパフォーマンスなWebアプリケーション開発に向いています。
サーバーサイド・クライアントサイドでJavascriptを動作させることができます。

node.js関連の記事

node.js 本家サイト

node.js node.jsスクリプトをforeverでデーモン化する

Javascript

node.jsスクリプトをデーモン化するツールにforeverというものがあります。
https://github.com/nodejitsu/forever

foreverは起動したnode.jsスクリプトの死活監視を行い、停止した場合は自動的に再起動します。

mmonit/Upstart/daemontools等、同様な機能を持つツールと比較しと、node.jsとの親和性が高くお手軽なことがメリットです。また、node.jsスクリプトからインスタンスを生成して操作することが可能です。

以下Version 0.7.2で確認した内容になります。

インストール

 npm install forever -g

※プログラムから利用する場合はローカルインストールしたほうが良いです。

 cd /path/to/project
 npm install forever

主なオプションは下記の通りです。

node.jsスクリプトの起動

 forever start app.js

実行中スクリプトの表示

 forever list

実行中スクリプトの停止や再起動

 forever stop
 forever stopall
 forever restart

引数

forever -hでヘルプが表示されます

 forever [action] [options] SCRIPT [script-options]

アクション

    start               Start SCRIPT as a daemon
    stop                Stop the daemon SCRIPT
    stopall             Stop all running forever scripts
    restart             Restart the daemon SCRIPT
    list                List all running forever scripts
    config              Lists all forever user configuration
    set <key> <val>     Sets the specified forever config <key>
    clear <key>         Clears the specified forever config <key>
    logs                Lists log files for all forever processes
    logs <script|index> Tails the logs for <script|index>
    columns add <col>   Adds the specified column to the output in `forever list`
    columns rm <col>    Removed the specified column from the output in `forever list`
    columns set <cols>  Set all columns for the output in `forever list`
    cleanlogs           [CAREFUL] Deletes all historical forever log files

オプション

    -m  MAX          Only run the specified script MAX times スクリプトの起動回数制限 
    -l  LOGFILE      Logs the forever output to LOGFILE foevert本体のログ
    -o  OUTFILE      Logs stdout from child script to OUTFILE 子スクリプト標準出力のログ 
    -e  ERRFILE      Logs stderr from child script to ERRFILE 子スクリプト標準エラー出力のログ 
    -p  PATH         Base path for all forever related files (pid files, etc.)
    -c  COMMAND      COMMAND to execute (defaults to node) 実行するコマンド(デフォルトはnode)
    -a, --append     Append logs ログを追記する 
    --pidfile        The pid file
    --sourceDir      The source directory for which SCRIPT is relative to
    --minUptime      Minimum uptime (millis) for a script to not be considered "spinning" 最低使用時間(ミリ秒)
    --spinSleepTime  Time to wait (millis) between launches of a spinning script. 実行中スクリプトの起動待ち時間
    --plain          Disable command line colors
    -d, --debug      Forces forever to log debug output
    -v, --verbose    Turns on the verbose messages from Forever
    -s, --silent     stdout/stderrへの出力を抑制する Run the child script silencing stdout and stderr
    -w, --watch      Watch for file changes ファイル変更を監視する 
    -h, --help       You're staring at it

node.jsアプリからforeverインスタンスを操作する

node.jsスクリプト内からforeverモジュールを使うことができます。

   var forever = require('forever');
 
   var child = new (forever.Monitor)('your-filename.js', {
     max: 3,
     silent: true,
     options: []
   });
  child.on('exit', this.callback);
  child.start();

node.js以外のプログラムをデーモン化する

node.jsスクリプトからperlワンライナーをデーモン化する例です。

 var forever = require('forever');
 var child = forever.start([ 'perl', '-le', 'print "moo"' ], {
   max : 1,
   silent : true
 });

サーバー起動時に自動的にforeverを自動開始する

/etc/rc.localに記述するのが簡単です。
/etc/rc.localの記述例です。

 /usr/local/bin/node /usr/local/bin/forever start \
   -p /var/run/forever \
   --pidfile /var/run/node-app.pid \
   -l /var/log/node-app.log -a \
   -d /home/node/ \
   /home/node/app.js

node.js Hello Worldを表示させる

Javascript

node.js Hello Worldを表示させる

node.js version 0.2.2

node.js インストール]]で[[node.jsをWebサーバーにインストールし終わったら、次はHello Worldを表示させてみます。

次のようなスクリプトを書いて、example.jsという名前でWebサーバーに保存します。
内容は、8124番のポートでこのWebサーバーに接続すると、「Hello World」が表示される、というものです。

 var http = require('http');
 
 http.createServer(function (request, response) {
   response.writeHead(200, {'Content-Type': 'text/plain'});
   response.end('Hello World\n');
 }).listen(8124);
  
 console.log('Server running at http://127.0.0.1:8124/');

サーバー上で、このexample.jsをnodeというコマンドで実行します。

 # node example.js
 Server running at http://127.0.0.1:8124/

と表示されたでしょうか?
されていれば、動作しています。

これで、このWebサーバーのどこに接続しても、ポート番号8124で接続すれば、「Hello World」と表示されるかと思います。

 http://Webサーバーのアドレス:8124/以下任意のパス

Webシステム開発のご依頼はこちら