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 시니^^
DB/NoSQL/Redis2014. 9. 15. 19:08

$ wget http://download.redis.io/releases/redis-2.8.15.tar.gz $ tar xvfz redis-2.8.15.tar.gz $ cd redis-2.8.15 $ make -j4 $ make install -j4 ###### /etc/init.d/ 추가되도록 install############################# ###### vi /etc/init.d/redis_6379 열어보면 실행방식 자세히 알 수 있음 $ cd utils/ $ ./install_server.sh Welcome to the redis service installer This script will help you easily set up a running redis server Please select the redis port for this instance: [6379] ###포트지정하면됨 Selecting default: 6379 Please select the redis config file name [/etc/redis/6379.conf] Selected default - /etc/redis/6379.conf Please select the redis log file name [/var/log/redis_6379.log] Selected default - /var/log/redis_6379.log Please select the data directory for this instance [/var/lib/redis/6379] Selected default - /var/lib/redis/6379 Please select the redis executable path [/usr/local/bin/redis-server] Selected config: Port : 6379 Config file : /etc/redis/6379.conf ##설정파일 Log file : /var/log/redis_6379.log ##로그파일 Data dir : /var/lib/redis/6379 Executable : /usr/local/bin/redis-server Cli Executable : /usr/local/bin/redis-cli Is this ok? Then press ENTER to go on or Ctrl-C to abort. Copied /tmp/6379.conf => /etc/init.d/redis_6379 Installing service... Successfully added to chkconfig! Successfully added to runlevels 345! Starting Redis server... Installation successful! ###################################################### ### redis 실행######################################## $ /etc/init.d/redis_6379 start Starting Redis server... ### redis 중지######################################## $ /etc/init.d/redis_6379 stop Stopping ... Redis stopped ### 커맨드라인 콘솔모드 접속 ######################### $ redis-cli 127.0.0.1:6379>


Posted by 시니^^
Programming/node.js2014. 9. 15. 18:21
$ yum install gcc gcc-c++
$ yum install openssl-devel make

$ wget http://nodejs.org/dist/v0.10.31/node-v0.10.31.tar.gz
※ http://nodejs.org/download/ 최신버젼받기

$ tar xvfz node-v0.10.31.tar.gz
$ cd node-v0.10.31

$ ./configure --prefix=/data/nodejs
{ 'target_defaults': { 'cflags': [],
                       'default_configuration': 'Release',
                       'defines': [],
                       'include_dirs': [],
                       'libraries': []},
  'variables': { 'clang': 0,
                 'gcc_version': 44,
                 'host_arch': 'x64',
                 'node_install_npm': 'true',
                 'node_prefix': '/data/nodejs',
                 'node_shared_cares': 'false',
                 'node_shared_http_parser': 'false',
                 'node_shared_libuv': 'false',
                 'node_shared_openssl': 'false',
                 'node_shared_v8': 'false',
                 'node_shared_zlib': 'false',
                 'node_tag': '',
                 'node_unsafe_optimizations': 0,
                 'node_use_dtrace': 'false',
                 'node_use_etw': 'false',
                 'node_use_openssl': 'true',
                 'node_use_perfctr': 'false',
                 'node_use_systemtap': 'false',
                 'python': '/usr/bin/python',
                 'target_arch': 'x64',
                 'v8_enable_gdbjit': 0,
                 'v8_no_strict_aliasing': 1,
                 'v8_use_snapshot': 'true',
                 'want_separate_host_toolset': 0}}
creating  ./config.gypi
creating  ./config.mk

$ make && make install

##### bin Path는 계정 및 shell환경에 맞게 profile 에 등록하기##
$ vi /root/.bash_profile
PATH=$PATH:$HOME/bin
PATH=$PATH:/data/nodejs/bin ##nodjs bin등록
export PATH
source /root/.bash_profile
##############################################################

$ /data/nodejs/bin/node -v
v0.10.31


## npm 이용한 forever 데몬프로그램 설치########################
$ /data/nodejs/bin/npm install -g forever 

## npm 이용한 socket.io 설치###################################
$ /data/nodejs/bin/npm install -g socket.io


Posted by 시니^^
Programming/node.js2014. 9. 15. 15:49

Node.js 책 잠시 보고 만든 샘플입니다.

그냥 참고용으로!!ㅎㅎ


1. Server Side Node.js Socket.io

  1. var io = require('socket.io').listen(80);
  2. var clients = {};
  3. io.sockets.on('connection', function (socket){
  4. //입장 및 닉네임체크
  5. socket.on('create_nickname',function(nickname,returnFunction){
  6. //닉네임중복체크
  7. var returnCode = 1;
  8. for ( var i in clients ){
  9. if ( clients[i] == nickname ){
  10. returnCode = -1;
  11. break;
  12. }
  13. }
  14. //닉네임체크확인 결과 전달
  15. returnFunction(returnCode);
  16. //닉네임체크 유효화됨
  17. if ( returnCode == 1 ) {
  18. //클라이언트 닉네임등록
  19. clients[socket.id] = nickname;
  20. //새접속자로인한 전체 유저리스트 전달함
  21. io.sockets.emit('user_list',clients);
  22. //전체유저 메세지전송
  23. io.sockets.emit('msgPush',{"nickname":"시스템","msg":clients[socket.id]+" 유저가 입장하셨습니다."});
  24. console.log('CONNECT : ',nickname+' ['+socket.id+'] '+'('+Object.keys(clients).length+'명)');
  25. }
  26. });
  27. socket.on('msgSend',function(data){
  28. //자신을 제외한 전체유저에게 메세지전송
  29. socket.broadcast.emit('msgPush',data);
  30. /*
  31. *socket.emit('msgPush',data);//자신에게만 보낼때
  32. *socket.broadcast.emit('msgPush',data);//자신제외 전체유저
  33. *io.sockets.emit('msgPush',data);//자신포함 전체유저에게
  34. *io.sockets.in(socket_id).emit('msgPush',data);//특정유저에게 귓속말시 socket_id추가입력하면됨
  35.     *io.of('namespace').emit('msgPush', data); //of 지정된 name space의 유저
  36. */
  37. console.log('Chat Msg : ','['+data['nickname']+'] '+data['msg']);
  38. });
  39. //접속종료시처리
  40. socket.on('disconnect', function(){
  41. if ( clients[socket.id] ){
  42. //유저이탈 메세지전달
  43. io.sockets.emit('msgPush',{"nickname":"시스템","msg":clients[socket.id]+" 유저가 나가셨습니다."});
  44. console.log('DISCONNECT : ', clients[socket.id]);
  45. //이탈유저닉네임삭제
  46. delete clients[socket.id];
  47. //유저이탈 전체유저리스트 갱신
  48. io.sockets.emit('user_list',clients);
  49. }else{
  50. console.log('NOT USER DISCONNECT : ', socket.id);
  51. }
  52. });
  53. });


2. Client

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Chat</title>
  6. </head>
  7. <body>
  8. <div id="chatJoin">
  9. <form id="chatJoinForm">
  10. 대화명 : <input id="nickname" name="nickname" type="text"> <input type="submit" value="입장">
  11. </form>
  12. </div>
  13. <div id="chatRoom" style="display:none;">
  14. <div id="msgList" style="float:left;width:500px;height:300px;border:1px solid #1D365D;overflow:auto;"></div>
  15. <div style="float:left;width:100px;height:300px;border:1px solid #1D365D;margin-left:3px;">
  16. <div style="border-bottom:1px solid #1D365D;">접속자</div>
  17. <div id="userList"></div>
  18. </div>
  19. <div style="clear:both;">
  20. <form id="chatMsgForm">ChatMsg : <input id="msgText" name="msg" type="text"> <input type="submit" value="전송"></form>
  21. </div>
  22. </div>
  23. </body>
  24. <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
  25. <script type="text/javascript" src="socket.io.js"></script>
  26. <script type="text/javascript">
  27. $(function(){
  28. var socket;
  29. function createNickname(nickName){
  30. socket.emit('create_nickname',nickName,function(returnCode){
  31. if ( returnCode == 1 ){
  32. //정상적인 닉네임
  33. $('#chatJoin').hide();
  34. $('#chatRoom').show();
  35. $('#msgText').focus();
  36. }else{ //아니면 닉네임중복됨
  37. alert('존재하는 닉네임입니다.');
  38. $('#nickname').focus();
  39. socket.disconnect();
  40. }
  41. });
  42. }
  43. function msgAdd(data){
  44. var sHtml = '<div><span style="color:blue;">'+data['nickname']+'</span> : '+data['msg']+'</div>';
  45. $('#msgList').append(sHtml);
  46. $("#msgList").scrollTop($("#msgList")[0].scrollHeight);
  47. }
  48. $('#chatMsgForm').submit(function(event){
  49. event.preventDefault();
  50. var data = {"nickname":$('#nickname').val(),"msg":$('#msgText').val()}
  51. msgAdd(data);
  52. $('#msgText').val('');
  53. $('#msgText').focus();
  54. //서버에 입력메세지전달
  55. socket.emit('msgSend', data);
  56. });
  57. $('#chatJoinForm').submit(function(event){
  58. event.preventDefault();
  59. if ( !$('#nickname').val() ){
  60. alert("닉네임을 입력해주세요");
  61. $('#nickname').focus();
  62. return false;
  63. }
  64. /*
  65. *https://github.com/automattic/socket.io-client
  66. */
  67. socket = io.connect('http://127.0.0.1', {'forceNew':true,reconnection:false});
  68. socket.on('connect', function () {
  69. createNickname($('#nickname').val());
  70. });
  71. socket.on('user_list',function(clients){
  72. //심플테스트 버젼이라서 삭제하고 새로 갱신하는방안
  73. $('#userList').html('');
  74. for ( var i in clients ){
  75. if ( clients[i] == $('#nickname').val() ){
  76. sHtml = '<div style="font-weight:bold;">'+clients[i]+'</div>';
  77. }else{
  78. sHtml = '<div>'+clients[i]+'</div>';
  79. }
  80. $('#userList').append(sHtml);
  81. }
  82. });
  83. socket.on('msgPush',function(data){
  84. msgAdd(data);
  85. });
  86. socket.on('disconnect', function(){
  87. $('#msgList').html('');
  88. $('#nickname').val('');
  89. $('#chatJoin').show();
  90. $('#chatRoom').hide();
  91. alert('Server Disconnect');
  92. });
  93. socket.on('connect_error', function (data) {
  94. alert('CONNECT_ERROR : '+data);
  95. });
  96. });
  97. });
  98. </script>
  99. </html>


Posted by 시니^^
Programming/node.js2014. 9. 13. 11:44

메뉴얼 사이트

 - Application :  http://expressjs.com/api.html#express

 - Request : http://expressjs.com/api.html#req.params

 - Response :  http://expressjs.com/api.html#res.status

 - Router : http://expressjs.com/api.html#router

 - Middleware : http://expressjs.com/api.html#middleware.api


테스트 샘플자료 (자세한 내용은 위에 API 참조하면 방대함 정규식처리등 많음)

  1. var express = require('express'), http = require('http');
  2. var bodyParser = require('body-parser');
  3. var app = express();
  4. app.use(bodyParser());
  5. app.all('*', function( req, res, next){
  6. res.writeHead(200,{
  7. "Content-Type" : "text/plain"
  8. });
  9. next();
  10. });
  11. app.get("/", function( req, res){
  12. res.end("HOME DIR : /");
  13. });
  14. app.get("/test", function( req, res){
  15. res.end("HOME DIR : /test");
  16. });
  17. app.get("/params/:user", function( req, res){
  18. var sText = " Params : "+req.params.user; // OR req.param('user')
  19. sText += "\n GET : "+req.query.q; //search?q=test OR req.param('q')
  20. sText += "\n POST : "+req.param('name'); //POST name=tobi
  21. //sText += "Cookie : "+req.cookies.name; // Cookie: name=tj
  22. sText += "\n ip : "+req.ip; // req.ips When "trust proxy" is `true`, parse the "X-Forwarded-For"
  23. res.end(sText);
  24. });
  25. app.get("*", function( req, res){
  26. res.end("NOT PAGE");
  27. });
  28. http.createServer(app).listen(80, '127.0.0.1');
  29. console.log('HTTP URL : http://127.0.0.1:80/');


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

자세한 내용은 메뉴얼 참조 http://nodejs.org/api/globals.html#globals_global


Global Objects

 - global

 - process

 - console

 - Class: Buffer

 - require()

 - require.resolve()

 - require.cache

 - require.extensions

 - __filename

 - __dirname

 - module

 - exports

 - setTimeout(cb, ms)

 - clearTimeout(t)

 - setInterval(cb, ms)

 - clearInterval(t)


변수류

__filename : 실행중인 경로포함 파일이름

__dirname : 실행중인 파일 경로까지만


실행한 Process 정보

 - http://nodejs.org/api/process.html#process_process_versions



Posted by 시니^^
Programming/JS/Jquery/Ajax2014. 9. 11. 12:05

jQuery Table Plugin 괜찮은 것 소개


메뉴얼 : http://mottie.github.io/tablesorter/docs/index.html


데모http://mottie.github.io/tablesorter/docs/index.html#Demo


tablesorter Bootstrap LESS theme 도 지원함


아래 샘플 보면 row 추가삭제에 대한 설명이나 페이징에 대한 설명도 잘 나와있다.

샘플설명자료http://mottie.github.io/tablesorter/docs/index.html#Examples


그리고 다양한 추가 플로그인 존재하여서 관리툴 개발시 상당히 유용함

Plugins / Widgets
 these widgets are included in the jquery.tablesorter.widgets.js file (except for extra filter formatter functions) 
 this widget is included with the plugin core.


Posted by 시니^^
Programming/PHP2014. 9. 4. 15:43


Anonymous functions - http://php.net/manual/ro/functions.anonymous.php


있다는 것만 알지.. 사용하지 않았다.. 

그런데 구글링 중 괜찮은 활용 방법을 찾아서!! 왠지 jquery 하는듯한 느낌은 뭐지...;;

 - 특정 배열값 파싱하거나 재구성할때 for문 안돌리고 array_map 이용할때 괜찮은듯함.

예) http://stackoverflow.com/questions/13435747/how-can-i-remove-the-file-extension-from-each-string-in-a-php-array


  1. <?php
  2. # your array
  3. $slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');
  4. # if you have PHP >= 5.3, I'd use this
  5. $slike = array_map(function($e){
  6. return pathinfo($e, PATHINFO_FILENAME);
  7. }, $slike);
  8. # if you have PHP <= 5.2, use this
  9. $slike = array_map('pathinfo', $slike, array_fill(
  10. 0, count($slike), PATHINFO_FILENAME
  11. ));
  12. # dump
  13. print_r($slike);
  14. /*print
  15. Array
  16. (
  17. [0] => 1
  18. [1] => 253455
  19. [2] => 32
  20. [3] => 477
  21. )
  22. */
  23. ?>


※ 단 PHP 5.3 이상부터 가능함!

Posted by 시니^^