<?php
error_reporting(E_ALL^E_NOTICE);
function ss_get_redis_client($a_config, $s_f)
{
try{
$o_r = new Redis();
$o_r->connect(
$a_config['host'],
$a_config['port'],
$a_config['timeout'],
$a_config['reserved'],
$a_config['retryInterval'],
$a_config['readTimeout']
);
if ($a_config['auth']) {
$o_r->auth($a_config['auth']);
}
return $o_r;
} catch (RedisException $e){
ss_log($s_f, $e->getCode() . ':' . $e->getMessage());
return ss_get_redis_client($a_config, $s_f);
}
}
function ss_log($s_f, $s_data)
{
file_put_contents($s_f, $s_data . "\n", FILE_APPEND);
}
$a_all_config = array(
'error_log_file' => 'ss_error.txt',
'redis' => array(
'host' => '1270.0.01',
'port' => '5678',
'timeout' => 0.5,
'reserved' => null,
'retryInterval' => 0,
'readTimeout' => 0.5,
'auth' => '',
),
'swoole' => array(
'daemonize' => 1,
'task_ipc_mode' => 2,
'worker_num' => 6,
'max_request' => 0,
'dispatch_mode' => 3,
),
);
$http = new \swoole_http_server("0.0.0.0", 9527);
$a_all_config = require 'config.php';
$_config = $a_all_config['swoole'];
$s_log_file = $a_all_config['error_log_file'];
$a_redis_config = $a_all_config['redis'];
$http->set($_config);
$http->on('WorkerStart', function ($serv, $worker_id) use($a_redis_config, $s_log_file) {
$serv->redis = ss_get_redis_client($a_redis_config, $s_log_file);
$serv->getcount = 0;
});
$http->on('request', function ($request, $response) use($http, $a_redis_config, $s_log_file) {
if ($http->getcount > 20) {
// || $http->redis->ping() != '+PONG'){
$http->redis = ss_get_redis_client($a_redis_config, $s_log_file);
$http->getcount = 0;
}
$s_key = $request->get['k'];
if ($s_key) {
try {
$s_r = $http->redis->get($s_key);
} catch (RedisException $e) {
ss_log($s_log_file, $e->getCode() . ':' . $e->getMessage());
$http->redis = ss_get_redis_client($a_redis_config, $s_log_file);
$http->getcount = 0;
$s_r = $http->redis->get($s_key);
}
$http->getcount++;
}
$s_r = $s_r ? : ' ';
$response->write($s_r);
$response->end();
});
$http->start();
*每个woker进程单独一个redis客户端,这里有个坑,单独的客户端重复使用时达到一定的次数 就会变得效率低下,原因未明,只好达到一定次数放弃连接,换一个 *