Redis + predis | memcachedの代わりにRedisを使ってみる。
http://redis.io
http://redis.io/clients
memcachedを利用していた表示データをredisにしてみます。
消えても良いのですが、データが出来るまで寂しいので。
daily rankingやpublic activityとか
*永続的なmemachedですが、メモリーサイズより大きいデータは扱えないので、あくまでもmemcachedの代替。Virtual Memory機能はあるが非推奨。
1. redis install
# yum list redis redis.x86_64 2.0.3-2.el5 epel # yum install redis Installing: redis x86_64 2.0.3-2.el5 epel 303 k
config
http://redis.io/topics/data-types-intro
keyの付け方がフムフム。
» Try to stick with a schema. For instance “object-type:id:field” can be a nice idea, like in “user:1000:password”. I like to use dots for multi-words fields, like in “comment:1234:reply.to”.
First steps with Redis lists : リストは、ランキングに最適っぽい。
Set : グルーピングに使うのかな
http://redis.io/topics/twitter-clone
twitterの動き、list,setを利用して簡単にclone。分かりやすい。key-valueやるときにこれを一回触るのは良いかもしれない。
少し使ってみた感じkeysが使えたりlist,setがあるので、keyの階層構造にかなり良いかもしれない。
* config
include /etc/redis.conf # pidfile /home/junichi/data/redis.pid # port 52131 # bind 127.0.0.1 # Specify the log file name. Also 'stdout' can be used to force logfile /home/junichi/log/redis/redis.log # The working directory. dir /home/junichi/data/redis/ # maxclients 30 timeout 10 # maxmemory 16M
* start
# redis-server /home/junichi/conf/redis.conf # netstat -na|grep 52131 tcp 0 0 127.0.0.1:52131 0.0.0.0:* LISTEN
* client test with host and port.
$ redis-cli -p 52131 -h 127.0.0.1 redis> PING PONG redis> INFO redis_version:2.0.3 redis_git_sha1:00000000 redis_git_dirty:0 arch_bits:64 multiplexing_api:epoll process_id:23081 uptime_in_seconds:748 uptime_in_days:0 connected_clients:1 connected_slaves:0 blocked_clients:0 used_memory:781808 used_memory_human:763.48K changes_since_last_save:0 bgsave_in_progress:0 last_save_time:1327032046 bgrewriteaof_in_progress:0 total_connections_received:1 total_commands_processed:2 expired_keys:0 hash_max_zipmap_entries:64 hash_max_zipmap_value:512 pubsub_channels:0 pubsub_patterns:0 vm_enabled:0 role:master redis> SET mytest "Hello" OK redis> GET mytest "Hello" redis> DELETE mytest (error) ERR unknown command 'DELETE' redis> DEL mytest (integer) 1 redis> GET mytest (nil)
データを残して接続を閉じる。
redis> SET mytest "SAVE ME" OK redis> QUIT
サーバーを落とす。shutdownではなくて、プロセスを落としてみる。
$ ps ax|grep redis-server 23081 ? Ss 0:00 redis-server conf/redis.conf $ sudo kill -9 23081
起動してみる。
$ redis-cli -p 52131 -h 127.0.0.1 redis> GET mytest "SAVE ME"
保存されている。
ディスクに保存されるタイミングについて
* save,bgsave,shutdownを実行。重要なデータを入れた後は、bgsaveしておけば良いのかな。
* config のsave値になったとき
// 1個の更新で900秒後 save 900 1 // 10個の更新で300秒後 save 300 10 // 10000個で60秒後 save 60 10000
* 終了
redis> SHUTDOWN
logにbackground saveできないと警告が
# WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add ‘vm.overcommit_memory = 1′ to /etc/sysctl.conf and then reboot or run the command ‘sysctl vm.overcommit_memory=1′ for this to take effect.
faqに 3GBのデータを持っていてfree memoryが2GBの時エラーになると。つまり、redisをディスクに書き込むとき、同じサイズのメモリーが必要になるから、vm.overcommit_memoryを有効にしていないとエラーになる。自分の場合は、メモリが少ないのでかなりの確率でなるから必須と。
Short answer: echo 1 > /proc/sys/vm/overcommit_memory
And now the long one:
Redis background saving schema relies on the copy-on-write semantic of fork in modern operating systems: Redis forks (creates a child process) that is an exact copy of the parent. The child process dumps the DB on disk and finally exits. In theory the child should use as much memory as the parent being a copy, but actually thanks to the copy-on-write semantic implemented by most modern operating systems the parent and child process will share the common memory pages. A page will be duplicated only when it changes in the child or in the parent. Since in theory all the pages may change while the child process is saving, Linux can’t tell in advance how much memory the child will take, so if the overcommit_memory setting is set to zero fork will fail unless there is as much free RAM as required to really duplicate all the parent memory pages, with the result that if you have a Redis dataset of 3 GB and just 2 GB of free memory it will fail.
Setting overcommit_memory to 1 says Linux to relax and perform the fork in a more optimistic allocation fashion, and this is indeed what you want for Redis.
A good source to understand how Linux Virtual Memory work and other alternatives for overcommit_memory and overcommit_ratio is this classic from Red Hat Magazine, “Understanding Virtual Memory”.
次は、phpから利用。
2. predis install
http://redis.io/clients
predis か phpredisに星が付いています。
・predis
https://github.com/nrk/predis
・phpredis
http://code.google.com/p/phpredis/ https://github.com/nicolasff/phpredis
どっちでも良さそうだけど。
predisを使ってみる。
PHP >= 5.3 | Redis from 1.2 to 2.4
* download
$ git clone git://github.com/nrk/predis.git ./predis
自分の場合 autoloaderを自分で書いているので
namespace Predisのときは、Predisディレクトリを勝手に見るので、Predisディレクトリをリンクしておくだけ。
autoloaderを利用していなくても、
./predis/autoload.phpをインクルードするだけでOKです。
https://github.com/nrk/predis/wiki/Quick-tour
こんな感じで。
早速TEST
test.php
$redis = new Predis\Client(array(
‘host’ => ‘127.0.0.1’,
‘port’ => 52110
));
$redis->set(‘library’, ‘predis’);
$retval = $redis->get(‘library’);
echo $retval.”\n”;
OKでした。