在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官方文档说明,凑合能用。
//参数1 文件名 参数2 缩放比例 function _thumb($_filename,$_percent){ ob_clean();...
<?php /* *算法学习自百度.只是学习和记录 */ header("Content-type:text/html;charset=utf-8"); //1.设置奖项,id是奖项id,name是中奖名称,v是中奖概率 $arr =&n...
xmlrpc协议是通过http请求xml数据进行通信。webservice中和它相同的是soap。soap调用的确很简单,但是创建wsdl太繁琐,效率低下。xmlrpc很好的解决这个问题。(1).创建xmlrpc服务端(求和函数api)function getSum($method,$ar...
主要原理是通过PHP创建多个子进程,在子进程中发送进程闹钟信号,然后再监听闹钟信号中继续发送闹钟信号。同时通过父进程设置非阻塞运行。代码如下:<?php /** * 订单任务 */ class Order { &n...
(1).学习目标: 了解常见信号类型(百度PHP支持的信号类型),(2).相关函数学习: (2.1).pcntl_signal函数用于设置一个信号管理器接收进程信号,参数1:信号类型,参数2:回调函数,用于在接收到参数1类型的信...
最近在公司开发一个新的项目假设项目域名是a.com,需要接入b.com的单点登陆系统。(1).首先我们会在a.com的登陆页面用iframe引入b.com来显示登陆界面,实际上登陆验证操作都是在b.com上面(2).当b.com验证通过,会在前端ajax请求a.com的回调地址,这个回调地址目的就是...