swoole读取redis服务

<?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客户端,这里有个坑,单独的客户端重复使用时达到一定的次数 就会变得效率低下,原因未明,只好达到一定次数放弃连接,换一个 *

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值