在cli下运行消费数据,需要保持redis断线重连,虽然redis可以直接传递参数长连接,但是如果redis服务器异常关闭后再重启则需要重启php脚本,比较麻烦,所以写了一个redis断线重连简单版。
<?php class PRedis { /** * options * @var array */ protected $options = ['host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'timeout' => 0, 'expire' => 0, 'persistent' => false, 'prefix' => '']; /** * handler * @var null */ protected $handler = null; /** * Redis constructor. * @param array $options * @throws Exception */ public function __construct($options = []) { $this->options = array_merge($this->options, $options); $this->connect(false); } /** * connect * @param $throw * @throws RedisException */ protected function connect($throw = true) { try { $this->handler = new \Redis(); if ($this->options['persistent']) { $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']); } else { $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']); } if ('' != $this->options['password']) { $this->handler->auth($this->options['password']); } if (0 != $this->options['select']) { $this->handler->select($this->options['select']); } } catch (\RedisException$exception) { if ($throw) { throw $exception; } } } /** * __call * @param $name * @param $args * @return mixed * @throws */ public function __call($name, $args) { try { set_error_handler(function ($errno, $errStr) { restore_error_handler(); throw new RedisException($errStr, $errno); }); return $this->handler->{$name}(...$args); } catch (\RedisException$exception) { echo "断线重连:" . $exception->getMessage() . PHP_EOL; $this->connect(false); return false; } } } $redis = new PRedis(); $redisKey = 'key'; while (true) { //set $redis->set($redisKey, rand(1, 99)); //get $value = $redis->get($redisKey); if ($value) { echo $value . PHP_EOL; } //sleep sleep(1); }
可以在断线重连异常中适当ping()来决定是否真正去连接,并且建议增加间隔多久连接一次。tp中mysql的断线重连是依赖于错误信息的关键字,或许在redis中断线重连也可以参考,毕竟异常不一定都是redis断开连接,可以从异常信息中提取关键字来精确分析,当然ping一下更简单。也没有来得及去看redis官方文档说明,凑合能用。
php7.1引入了PHP异步信号处理函数pcntl_async_signals() 来处理阻塞问题。在php7之前信号处理方式有2种,第一种是基于ticks来每执行一行代码来触发执行信号监听,第二种是直接while(true){ //监听信号 }第一种方式如果某行的代码阻塞时间较长会影响...
最近在项目中处理一个关于商品数据重复需要删除多余的商品记录,但是删除一条商品必然要把关联的其他表商品的id和其他商品信息更换为正确的,删除一个商品记录,同时要去修改100多张表的关联商品数据,在项目中引用了tp orm 1.2版本,由于项目是php5.6版本,没法使用最新orm,在代码中每处理1个商...
(1).今天遇到一件奇怪的事情,在event事件中是无法自定义异常处理,例如我们使用set_exception_handler来统一处理异常。例如下面的代码:<?php error_reporting(E_ALL); set_error_handler(function ($errn...
安装php-redis扩展提示No releases available for package我直接去php官网下载redis扩展.tgz文件,然后直接用pecl安装本地文件pecl install ./redis.tgz...
场景:模拟验证码发送。仅做代码演示。(1).创建一个验证码发送接口sendCaptcha/** * 发送验证码 */ public function sendCaptcha() { //外部参数(获...
今天朋友面试遇到的问题:php如何阻止一个类被序列化,首先我想到的是使用serialize函数进行序列化对象首先会检查对象是否存在__sleep方法,如果有的话先调用__sleep方法。(1).普通序列化对象代码:class member {  ...