使用Twemproxy实现Redis连接池

原理:php和twemproxy代理在同一服务器下,通过unix socket通信,proxy保持对远端redis的长连接,这样可以减少php直连redis的网络开销

 

安装需要的工具

yum install autoconf

yum install automake

yum install libtool

下载安装Twemproxy

wget https://codeload.github.com/twitter/twemproxy/zip/master

unzip twemproxy-master.zip

cd twemproxy-master/  

./configure --prefix=/usr/local/twemproxy

make && make install

设置环境变量

echo 'PATH=$PATH:/usr/local/twemproxy/sbin' >> /etc/profile

source /etc/profile

创建conf目录

cd /usr/local/twemproxy

mkdir conf



按照类似如下配置和CPU数量相同的配置数(我的CPU为双核),监听不同的socket:

redis1.yml
instance:
    listen: /usr/local/twemproxy/nutcracker1.sock
    hash: fnv1a_64
    distribution: ketama
    auto_eject_hosts: true
    redis: true
    server_retry_timeout: 2000
    server_failure_limit: 1
    servers:
        - 127.0.0.1:6379:1
      

redis2.yml
instance:
    listen: /usr/local/twemproxy/nutcracker2.sock
    hash: fnv1a_64
    distribution: ketama
    auto_eject_hosts: true
    redis: true
    server_retry_timeout: 2000
    server_failure_limit: 1
    servers:
        - 127.0.0.1:6379:1

     

运行两个实例


nutcracker -c /usr/local/twemproxy/conf/redis1.yml -m 512 -s 11111 -d
nutcracker -c /usr/local/twemproxy/conf/redis2.yml -m 512 -s 22222 -d


[root@www html]# ps -ef | grep nut
root     19266  8958  0 08:26 pts/4    00:00:00 grep --color=auto nut
root     28250     1  0 07:29 ?        00:00:00 nutcracker -c /usr/local/twemproxy/conf/redis1.yml -m 512 -s 11111 -d
root     30225     1  0 07:30 ?        00:00:00 nutcracker -c /usr/local/twemproxy/conf/redis2.yml -m 512 -s 22222 -d

PHP程序

connect('/usr/local/twemproxy/nutcracker' .rand(1,2) . '.sock');
$con = $redis->connect('127.0.0.1', '6379');

$redis->set('test_twemproxy', 'test_twemproxy');
echo $redis->get('why');

$redis->close();

配置参考:https://www.iteye.com/blog/cpjsjxy-2090333

 

 

(PS:如果将同一实例的配置servers配置多台redis服务,可根据相应分配算法实现集群)

你可能感兴趣的:(redis)