Programming/node.js2014. 9. 20. 12:14

node.js는 싱글프로세스다 보니까 한개 데몬당 하나의 CPU 코어만 이용한다.


이걸 보완하고 위해서 클러스터를 이용한다.


자세한 api 설명은 아래 내용을 참고 하면 된다.

http://nodejs.org/api/cluster.html


1. 기본 샘플 사용 방법

  1. var cluster = require('cluster');
  2. var http = require('http');
  3. var numCPUs = require('os').cpus().length;
  4. if (cluster.isMaster) {
  5. //cpu갯수만큼 프로세스 실행
  6. for (var i = 0; i < numCPUs; i++) {
  7. cluster.fork();
  8. }
  9. cluster.on('exit', function(worker, code, signal) {
  10. console.log('worker ' + worker.process.pid + ' died');
  11. //서버가 죽었을시 프로세스 자동 추가 실행 또는 알아서 알람sms나 이메일등 모니터링 알람 처리
  12. cluster.fork();
  13. });
  14. } else {
  15. // Workers can share any TCP connection
  16. // In this case its a HTTP server
  17. http.createServer(function(req, res) {
  18. res.writeHead(200);
  19. res.end("hello world\n");
  20. }).listen(8001);
  21. console.log('PID ['+process.pid+'] HTTP SERVER');
  22. }


2. 프로세스 정보

$ node cluster.js PID [1571] HTTP SERVER PID [1573] HTTP SERVER PID [1574] HTTP SERVER PID [1575] HTTP SERVER $ ps aux | grep node root 1569 node cluster.js ### 클러스터 마스터node ###### root 1571 /data/nodejs/bin/node /data/nodejs/www/cluster.js root 1573 /data/nodejs/bin/node /data/nodejs/www/cluster.js root 1574 /data/nodejs/bin/node /data/nodejs/www/cluster.js root 1575 /data/nodejs/bin/node /data/nodejs/www/cluster.js


3. Kill 시 자동으로 프로세스 추가 실행됨

$ kill 1571
worker 1571 died
PID [1617] HTTP SERVER

$ ps aux | grep node
root      1569   node cluster.js
root      1573   /data/nodejs/bin/node /data/nodejs/www/cluster.js
root      1574   /data/nodejs/bin/node /data/nodejs/www/cluster.js
root      1575   /data/nodejs/bin/node /data/nodejs/www/cluster.js
root      1617   /data/nodejs/bin/node /data/nodejs/www/cluster.js


4. 추가적인 참고자료

Node JS 멀티코어 CPU 지원하기 - http://eclipse.or.kr/wiki/특집기사:Node_JS_멀티코어_CPU_지원하기

Cluster모듈에서 Socket.IO 사용하기 - http://blog.outsider.ne.kr/764




Posted by 시니^^
Programming/node.js2014. 9. 19. 11:53

출처 샘플 참고 사이트

http://www.hacksparrow.com/node-js-udp-server-and-client-example.html


1. UDP Server

  1. var PORT = 7001;
  2. var HOST = '127.0.0.1';
  3. var dgram = require('dgram');
  4. var server = dgram.createSocket('udp4');
  5. server.on('listening', function () {
  6. var address = server.address();
  7. console.log('UDP Server listening on ' + address.address + ":" + address.port);
  8. });
  9. server.on('message', function (message, remote) {
  10. console.log(remote.address + ':' + remote.port +' - ' + message);
  11. });
  12. server.bind(PORT, HOST);


2. UDP Client

  1. var PORT = 7001;
  2. var HOST = '127.0.0.1';
  3. var dgram = require('dgram');
  4. var message = new Buffer('TEST!');
  5. var client = dgram.createSocket('udp4');
  6. client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
  7. if (err) throw err;
  8. console.log('UDP message sent to ' + HOST +':'+ PORT);
  9. client.close();
  10. });


3. PHP UDP Client

  1. <?php
  2. $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  3. $in = 'test!';
  4. var_dump (socket_sendto($socket, $in,strlen($in), 0,'127.0.0.1',7001));
  5. socket_close($socket);
  6. ?>


Posted by 시니^^
Programming/node.js2014. 9. 18. 19:14

1. http/ querystring만 사용


  1. var http = require('http')
  2. ,qs = require('querystring');
  3. http.createServer(function (req, res) {
  4. if( req.url == '/' && req.method == 'POST'){
  5. var postBody = '';
  6. req.on('data', function (data) {
  7. postBody += data;
  8. });
  9. req.on('end', function () {
  10. var post = qs.parse(postBody);
  11. //post데이터확인
  12. console.log(post['postname']);
  13. });
  14. res.end('true');
  15. }else{
  16. res.writeHead(404, {'Content-Type': 'text/plain'});
  17. res.end('404 ERROR');
  18. }
  19. }).listen(8001);


2. http / express  / body-parser 사용


  1. var express = require('express')
  2. ,http = require('http')
  3. ,bodyParser = require('body-parser');
  4. var app = express();
  5. app.use(bodyParser.urlencoded({extended: true}));
  6. //app.use(bodyParser.json());
  7. app.post("/", function( req, res){
  8. res.writeHead(200,{"Content-Type" : "text/plain"});
  9. //post데이터확인
  10. console.log(req.param('postname',null));
  11. res.end('test');
  12. });
  13. app.use(function( req, res){
  14. res.writeHead(404,{"Content-Type" : "text/plain"});
  15. res.end('404 ERROR');
  16. });
  17. http.createServer(app).listen(8001);


Posted by 시니^^
Programming/PHP2014. 9. 18. 16:16



elephant.io https://github.com/Wisembly/elephant.io


1. elephantio.php -  elephant.io 다운로드 src폴더 데이터에 대한 include 또는 require 파일 만들기

  1. <?php
  2. $___ELEPHANTIO_DIR = dirname(__FILE__);
  3. require $___ELEPHANTIO_DIR.'/Client.php';
  4. require $___ELEPHANTIO_DIR.'/AbstractPayload.php';
  5. require $___ELEPHANTIO_DIR.'/EngineInterface.php';
  6. require $___ELEPHANTIO_DIR.'/Engine/AbstractSocketIO.php';
  7. require $___ELEPHANTIO_DIR.'/Engine/SocketIO/Session.php';
  8. require $___ELEPHANTIO_DIR.'/Engine/SocketIO/Version1X.php';
  9. require $___ELEPHANTIO_DIR.'/Exception/MalformedUrlException.php';
  10. require $___ELEPHANTIO_DIR.'/Exception/ServerConnectionFailureException.php';
  11. require $___ELEPHANTIO_DIR.'/Exception/SocketException.php';
  12. require $___ELEPHANTIO_DIR.'/Exception/UnsupportedActionException.php';
  13. require $___ELEPHANTIO_DIR.'/Exception/UnsupportedTransportException.php';
  14. require $___ELEPHANTIO_DIR.'/Payload/Decoder.php';
  15. require $___ELEPHANTIO_DIR.'/Payload/Encoder.php';
  16. ?>


2. client.php

  1. <?php
  2. include 'lib/elephantio/elephantio.php';
  3. /*
  4. * Version1X arg2 Option : ['context'=>[], 'debug'=>false,'wait'=>100*1000,'timeout'=>ini_get("default_socket_timeout")];
  5. */
  6. $EIO = new ElephantIO\Client(
  7. new ElephantIO\Engine\SocketIO\Version1X('http://127.0.0.1:8001',['timeout'=>5])
  8. );
  9. $EIO->initialize();
  10. $EIO->emit('msgIn', array('data1','data2') );
  11. $EIO->close();
  12. ?>


3. nodejs server

  1. var io = require('socket.io').listen(8001);
  2. io.sockets.on('connection', function (socket){
  3. socket.on('msgIn',function(msg){
  4. console.log('Msg In : ',msg);
  5. });
  6. socket.on('disconnect', function(){
  7. console.log('NOT USER DISCONNECT : ', socket.id);
  8. });
  9. });
  10. /*
  11. * debug
  12. * Msg In : [ 'data1', 'data2' ]
  13. * NOT USER DISCONNECT : NPmXDQpuVM9OFYl0AAAA
  14. */


Posted by 시니^^
Programming/PHP2014. 9. 18. 14:49

Github 주소

https://github.com/msgpack/msgpack-php


소스설치방법

$ wget https://github.com/msgpack/msgpack-php/zipball/master -O msgpack-php.zip
$ unzip msgpack-php.zip 
$ cd msgpack-msgpack-php-da24be3/
$ phpize
Configuring for:
PHP Api Version:         20121113
Zend Module Api No:      20121212
Zend Extension Api No:   220121212

$ ./configure
$ make && make install
Installing shared extensions:     /usr/lib64/php/modules/
Installing header files:          /usr/include/php/


$ cd /usr/lib64/php/modules/
$ ll | grep msgpack
-rwxr-xr-x 1 root root  388516 Sep 18 14:27 msgpack.so


##### php.conf 디렉토리에 맞게 ini 에 extension 등록하기! 안되면 php.ini등록해도됨
$ echo extension=msgpack.so > /etc/php.d/msgpack.ini 

##### 웹서버종류에 따라서 Apache Restart 또는 php-fpm restart
$ /etc/init.d/php-fpm restart

##### 최종확인
$ php -i | grep 'MessagePack Support'
MessagePack Support => enabled

<?php phpinfo() ?> 
MessagePack Support enabled
Session Support enabled
extension Version   0.5.6-dev
header Version  0.5.4
Directive   Local Value Master Value
msgpack.error_display   On  On
msgpack.illegal_key_insert  Off Off
msgpack.php_only    On  On


Posted by 시니^^
Programming/PHP2014. 9. 16. 18:04

1. Redis List 데이터 사용 샘플소스


  1. <?php
  2. $redis = new Redis();
  3. try {
  4. $redis->connect('127.0.0.1', 6379, 2.5);//2.5 sec timeout
  5. //Auth Password(redis.conf requirepass)
  6. //$redis->auth('foobared');
  7. } catch (Exception $e) {
  8. exit( "Cannot connect to redis server : ".$e->getMessage() );
  9. }
  10. // //DB Select
  11. if ( !$redis->select(0) ){
  12. exit( "NOT DB Select");
  13. }
  14. $redis->delete('weblog:ws1');
  15. //rPush 맨아래 배열로 입력
  16. $redis->rPush('weblog:ws1', 'log1');
  17. $redis->rPush('weblog:ws1', 'log2');
  18. $redis->rPush('weblog:ws1', 'log3');
  19. $redis->rPush('weblog:ws1', 'log4');
  20. //lPush 첫번째 배열로 입력
  21. $redis->lPush('weblog:ws1', 'log5');
  22. //0~2번까지배열 가져오기
  23. var_dump($redis->lRange('weblog:ws1', 0, 2));
  24. //전체배열데이터 가져오기
  25. var_dump($redis->lRange('weblog:ws1', 0, -1));
  26. ?>

2. Redis 들어있는 데이터



3. 추가명령어 메뉴얼참조

https://github.com/nicolasff/phpredis#lists

blPop, brPop - Remove and get the first/last element in a list

brpoplpush - Pop a value from a list, push it to another list and return it

lIndex, lGet - Get an element from a list by its index

lInsert - Insert an element before or after another element in a list

lLen, lSize - Get the length/size of a list

lPop - Remove and get the first element in a list

lPush - Prepend one or multiple values to a list

lPushx - Prepend a value to a list, only if the list exists

lRange, lGetRange - Get a range of elements from a list

lRem, lRemove - Remove elements from a list

lSet - Set the value of an element in a list by its index

lTrim, listTrim - Trim a list to the specified range

rPop - Remove and get the last element in a list

rpoplpush - Remove the last element in a list, append it to another list and return it (redis >= 1.1)

rPush - Append one or multiple values to a list

rPushx - Append a value to a list, only if the list exists

Posted by 시니^^
Programming/PHP2014. 9. 16. 16:26


1. Redis Hash 데이터 사용 샘플 소스


  1. <?php
  2. $redis = new Redis();
  3. try {
  4. $redis->connect('127.0.0.1', 6379, 2.5);//2.5 sec timeout
  5. //Auth Password(redis.conf requirepass)
  6. //$redis->auth('foobared');
  7. } catch (Exception $e) {
  8. exit( "Cannot connect to redis server : ".$e->getMessage() );
  9. }
  10. // //DB Select
  11. if ( !$redis->select(0) ){
  12. exit( "NOT DB Select");
  13. }
  14. $redis->delete('user_list');
  15. $redis->hSet('user_list', 'uid1', 1);
  16. $redis->hSet('user_list', 'uid2', 2);
  17. $redis->hSet('user_list', 'uid3', 3);
  18. if ( $redis->hExists('user_list','uid1') ){
  19. echo "uid1 : ".$redis->hGet('user_list','uid1')."\n";
  20. }else{
  21. echo 'NOT_DATA';
  22. }
  23. //여러개 HASH 데이터 한번에 입력
  24. $redis->hMset('user_list', array('uid4' => 4, 'uid5' =>5));
  25. //여러개 HASH 데이터를 한번에 가져옴
  26. var_dump($redis->hMGet('user_list', array('uid4', 'uid5')));
  27. var_dump($redis->hGetAll('user_list'));
  28. /*
  29. * Print
  30. uid1 : 1
  31. array(2) {
  32. ["uid4"]=>
  33. string(1) "4"
  34. ["uid5"]=>
  35. string(1) "5"
  36. }
  37. array(5) {
  38. ["uid1"]=>
  39. string(1) "1"
  40. ["uid2"]=>
  41. string(1) "2"
  42. ["uid3"]=>
  43. string(1) "3"
  44. ["uid4"]=>
  45. string(1) "4"
  46. ["uid5"]=>
  47. string(1) "5"
  48. }
  49. */
  50. ?>


2. Redis 들어있는 데이터




3. 추가 명령어 메뉴얼 참조

https://github.com/nicolasff/phpredis#hashes

hDel - Delete one or more hash fields

hExists - Determine if a hash field exists

hGet - Get the value of a hash field

hGetAll - Get all the fields and values in a hash

hIncrBy - Increment the integer value of a hash field by the given number

hIncrByFloat - Increment the float value of a hash field by the given amount

hKeys - Get all the fields in a hash

hLen - Get the number of fields in a hash

hMGet - Get the values of all the given hash fields

hMSet - Set multiple hash fields to multiple values

hSet - Set the string value of a hash field

hSetNx - Set the value of a hash field, only if the field does not exist

hVals - Get all the values in a hash

hScan - Scan a hash key for members

Posted by 시니^^
Programming/PHP2014. 9. 16. 16:07

Connect와 기본 keys-and-strings 샘플자료


  1. <?php
  2. $redis = new Redis();
  3. try {
  4. $redis->connect('127.0.0.1', 6379, 2.5);//2.5 sec timeout
  5. //Auth Password(redis.conf requirepass)
  6. //$redis->auth('foobared');
  7. } catch (Exception $e) {
  8. exit( "Cannot connect to redis server : ".$e->getMessage() );
  9. }
  10. // //DB Select
  11. if ( !$redis->select(0) ){
  12. exit( "NOT DB Select");
  13. }
  14. $redis->set('key1','value1',10); //유효기간 10초
  15. echo $redis->get('key1');
  16. /*
  17. * print : value1
  18. */
  19. ?>


자세한 명령어 사용법은 아래 메뉴얼참조

https://github.com/nicolasff/phpredis#keys-and-strings


Strings

append - Append a value to a key

bitcount - Count set bits in a string

bitop - Perform bitwise operations between strings

decr, decrBy - Decrement the value of a key

get - Get the value of a key

getBit - Returns the bit value at offset in the string value stored at key

getRange - Get a substring of the string stored at a key

getSet - Set the string value of a key and return its old value

incr, incrBy - Increment the value of a key

incrByFloat - Increment the float value of a key by the given amount

mGet, getMultiple - Get the values of all the given keys

mSet, mSetNX - Set multiple keys to multiple values

set - Set the string value of a key

setBit - Sets or clears the bit at offset in the string value stored at key

setex, psetex - Set the value and expiration of a key

setnx - Set the value of a key, only if the key does not exist

setRange - Overwrite part of a string at key starting at the specified offset

strlen - Get the length of the value stored in a key


Keys

del, delete - Delete a key

dump - Return a serialized version of the value stored at the specified key.

exists - Determine if a key exists

expire, setTimeout, pexpire - Set a key's time to live in seconds

expireAt, pexpireAt - Set the expiration for a key as a UNIX timestamp

keys, getKeys - Find all keys matching the given pattern

scan - Scan for keys in the keyspace (Redis >= 2.8.0)

migrate - Atomically transfer a key from a Redis instance to another one

move - Move a key to another database

object - Inspect the internals of Redis objects

persist - Remove the expiration from a key

randomKey - Return a random key from the keyspace

rename, renameKey - Rename a key

renameNx - Rename a key, only if the new key does not exist

type - Determine the type stored at key

sort - Sort the elements in a list, set or sorted set

ttl, pttl - Get the time to live for a key

restore - Create a key using the provided serialized value, previously obtained with dump.

Posted by 시니^^
Programming/PHP2014. 9. 16. 12:42

Memcached는 써보았는데 Redis는 아직 테스트를 안해봐서 아래 설명만 우선링크


phpredis 설치방법은 아래 글 참조

http://opens.kr/53


세션 서버 사용 설명- https://github.com/nicolasff/phpredis#php-session-handler


phpredis can be used to store PHP sessions. To do this, configure session.save_handler andsession.save_path in your php.ini to tell phpredis where to store the sessions:


session.save_handler = redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2"


php.ini에서 위에 처럼 config 수정하는 방법도 있고 소스상에서 ini_set 으로 하는 방법도 있다.


Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime". You can change it with ini_set(). The session handler requires a version of Redis with the SETEXcommand (at least 2.0). phpredis can also connect to a unix domain socket: session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0.


아래 처럼 테스트 하니까 잘 된다. 


  1. <?php
  2. ini_set('session.save_handler', 'redis');
  3. ini_set('session.save_path', 'tcp://127.0.0.1:6379');
  4. //unix sock의 경우 아래처럼 그리고 & 파라미터로 database등 지정할수있는듯함
  5. //ini_set('session.save_path', 'unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0');
  6. ?>


Posted by 시니^^
Programming/PHP2014. 9. 16. 12:32


http://redis.io/clients 

=> 공식 사이트 들어가보면  아래 두가지를 추천하는 듯함

Predis ☺ ★ Repository JoL1hAHN Mature and supported

phpredis ☺ ★ Repository yowgi This is a client written in C as a PHP module.


아무래도 C로 작성된 PHP 모듈이 성능이 더 좋지 않을가?? 라는 생각에 아래 phpredis 하기로함
테스트는 해봐야겠지만.............
그리고 보니까...  https://github.com/nicolasff/phpredis#php-session-handler 도 지원함 좋다!!

설치방법 아래 참조

$ wget https://github.com/nicolasff/phpredis/zipball/master -O phpredis.zip
$ unzip phpredis.zip 
$ ll
drwxr-xr-x  5 root root   4096 Sep  3 04:27 nicolasff-phpredis-4c1f1bc

$ cd nicolasff-phpredis-4c1f1bc/
$ phpize 
Can't find PHP headers in /usr/include/php
The php-devel package is required for use of this command.

$ yum install php-devel #PHP devel 미설치시 설치하기!
$ phpize
Configuring for:
PHP Api Version:         20121113
Zend Module Api No:      20121212
Zend Extension Api No:   220121212

$ ./configure
$ make && make install
Installing shared extensions:     /usr/lib64/php/modules/

$ cd /usr/lib64/php/modules/
$ ll | grep redis
-rwxr-xr-x 1 root root  942112 Sep 16 12:11 redis.so

##### php.conf 디렉토리에 맞게 ini 에 extension 등록하기! 안되면 php.ini등록해도됨
$ echo extension=redis.so > /etc/php.d/redis.ini 


##### 웹서버종류에 따라서 Apache Restart 또는 php-fpm restart
$ /etc/init.d/php-fpm restart

##### 최종확인
$ php -i | grep 'Redis Version'
Redis Version => 2.2.5

<?php phpinfo() ?> 
redis
Redis Support => enabled
Redis Version => 2.2.5


Posted by 시니^^