Redis의 Subscribe를 이용하여 php 와 node간의 통신

redis의 subscribe 기능을 이용해서 php에서 nodejs로 실시간으로 데이타를 전송/반영할 수 있다.

php 에서 publish 명령을 이용하여 redis로 데이타 전송

$redis->publish('webcrawling', json_encode($row));
$redis->publish('pub', json_encode(array("pub"=>"user_pick_register", "data"=>array("pick"=>$pick_game, "feed"=>$feederinfo))));

nodejs 에서 subscribe를 이용하여 redis 의 데이타 수신

rSub.subscribe('webcrawling');

rSub.on("message", function(channel, message) {
  // channel mustbe webcrawling, and message be row
  console.log("channel");
  console.log("message");
                
  // Channel is e.g 'score.update'
  // client.emit(channel, message);
});

테스트 결과 subscribe는 master에서만 가능하다. 따라서 master에서 전송 받은 후 client로 전송해야 정상적인 결과가 나온다.

php와 연동하여 publish, subscribe 구현하기

publish.php

<?php 
$redis = new Redis();    
$redis->pconnect('127.0.0.1',6379);
  $redis->publish('chan-1', 'hello, world!'); // send message to channel 1.
  $redis->publish('chan-2', 'hello, world2!'); // send message to channel 2.
 
  print "\n";
  $redis->close();

subscribe.php

<?php

//forever -c php subscribe.php >> /var/log/php-subscribe.log &
function f($redis, $chan, $msg) {
    switch($chan) {
        case 'chan-1':
            print "get $msg from $chan\n";
            break;
        case 'chan-2':
            print "get $msg FROM $chan\n";
            break;
        case 'chan-3':
            break;
    }
}
ini_set('default_socket_timeout', -1);

$redis = new Redis();
$redis->pconnect('127.0.0.1', 6379);
//$redis->pconnect('myredisserver.test.com', 6378);
 
$redis->subscribe(array('chan-1', 'chan-2', 'chan-3'), 'f');
print "\n";
평점을 남겨주세요
평점 : 2.5
총 투표수 : 1