Redis连接超时 Error while writing bytes to the server.
问题描述:在使用Redis过程中遇到Error while writing bytes to the server. [tcp://127.0.0.1:6379],经排查是redis连接断开,redis serve配置的timeout时间为300s,中间逻辑处理过久导致
查看Redis服务器配置(默认是不开启的timeout=0,不开启则不会出现上面的问题,为什么要开启请参考:https://blog.51cto.com/coveringindex/2387539)
# Close the connection after a client is idle for N seconds (0 to disable)
timeout 300
本地模拟问题排查原因
使用环境:win7 + redis_version:3.0.504
修改redis配置timeout=5 (windows下改redis.windows.conf)
redis-server.exe .\redis.windows.conf
# Close the connection after a client is idle for N seconds (0 to disable)
timeout 5
使用测试:
$connection = Redis::connection();
while (true) {//Redis设置的timeout测试时间为5s
try {
var_dump($connection->ping());
// $aa = $connection->client()->disconnect();
$value = $connection->get('test');
var_dump($value);
echo "sleep 6s".PHP_EOL;
sleep(6);//Redis设置的timeout测试时间为5s
} catch (\Exception $e) {
echo $e->getMessage().PHP_EOL;//Error while writing bytes to the server. [tcp://127.0.0.1:6379]
$connection = Redis::connection();
}
}
测试结果:
执行代码时间超出redis配置的timeout则会出现Error while writing bytes to the server,这时需要重新连接redis
如果是在Laravel框架中使用出现该问题可以查redis 服务器是否设置timeout如果没设置可以修改config/database.php配置
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
'read_write_timeout' => 0,//添加一行
],
Predis配置中默认是60s https://github.com/nrk/predis/wiki/Connection-Parameters
如果Redis服务器设置了timeout可能还是得判断连接是否超时再重连处理