当前位置:首页 > 技术文章 > 正文内容

基于一次ContentDownload变慢而进行的网站性能优化

arlanguage5个月前 (12-15)技术文章38

平时运行无常的网站,突然出现了某个接口TTFB缓慢问题,于是乎开始定位和解决,先说明一下网站的技术栈:

编程语言:PHP、Javascript、Vue、Java

开发框架:Laravel、SpringBoot

中间件:Redis、Kafka、Nginx

数据库:Mysql、MongoDB

云服务:腾讯云(使用了CDN加速)


业务接口的逻辑:

页面发送一个ajax请求,业务处理这块,PHP这块只是作为一个中转过渡的作用,实际上业务的主要处理都是放在SpringBoot这边。页面请求Laravel的一个接口,接口中只是做了一些基本的参数校验,然后内部调用SpringBoot接口,接收到SpringBoot接口返回数据之后,PHP直接将数据返回给客户端。伪代码如下:

public function page(Request $Request){
        //参数校验
    
        //将请求数据包暂存redis,因为请求传参数据包比较大,这种方式可以减少传参数据的大小
        $redis_id = makeUuid();
        $WS->sessionSet($redis_id, json_encode($args), 120, true);

        //内部调用SpringBoot接口(使用的是内网IP)
        $apiData = InnerRequest::get($_SERVER['SERVER_NAME'],'application/page/handle',[
            'method' => 'page.get',
            'data' => $redis_id
        ]);

        if ($apiData['code'] != 200) {
            return response()->json(['code' => $apiData['code'], 'message' => $apiData['message']]);
        }

        //获取缓存数据
        $data = $WS->sessionGet($apiData['data']['data'], true);
        $WS->sessionRemove($apiData['data']['data'], true);
        if (empty($data)) {
            return response()->json(['code' => 500, 'message' => "无返回数据结果"]);
        }

        
        /**
         * 1、处理返回的对象数据包
         *  1.1:去掉不需要的字段
         */

        return response()->json($data);
    }

影响网页加载速度的因素

影响一个网站的因素是多方面的,我们大致可以列举一下:

1】服务器从磁盘中读取页面数据

2】页面静态文件数量以及大小

3】页面ajax请求数量

4】服务器的响应时间

5】服务器本身的性能

6】浏览器本地渲染和计算的时间


Chrome浏览器DevTools指标说明

分析网页加载速度,主要查看Timing指标,而Timing主要有以下几个维度:

1、Queuing

主要是资源加载的排队

  • 不可优化部分
    请求被渲染引擎推迟,如脚本/样式会优先,图片推迟。生成磁盘缓存条目所用的时间(通常非常迅速)。
  • 可优化部分
    请求已被暂停,以等待将要释放的不可用TCP套接字。
    浏览器线程池不是无限的,需要等待socket(TCP)释放。 合并小文件减少请求。 请求被暂停,HTTP 1上,浏览器仅允许每个源拥有六个TCP连接。
    主要是对服务器的保护。 可以把资源放到不同的域名上,参考`域名发散`。

2、Stalled/Blocking

请求等待发送所用的时间。Queuing中的所有原因加上代理协商所用的任何时间。

  • 不可优化部分
    Queuing中不可优化部分代理协商
  • 可优化部分
    Queuing中可优化部分相同的N次请求 缓存锁,一般资源加载不会加载相同的,但ajax有可能,加timestamp可解决。

3、Proxy Negotiation

与代理服务器连接协商所用的时间。

主要是浏览器通过代理服务器去服务目标服务,如本地代理Fiddler,一般无法优化。

4、DNS Lookup

DNS查询所用的时间

  • 可优化部分
    不要有太多的新域名(可能递归查询绕地球一圈),参考域名收敛。减少DNS解析路径(如果内部有很多DNS服务器解析)。

5、Initial Connection / Connecting

建立连接所用的时间,包括TCP 握手/重试和协商 SSL的时间。

6、SSL

完成SSL握手所用的时间。

  • 可优化部分
    需要区分好什么资源需要https,什么需要http。

7、Request Sent / Sending

发出网络请求所用的时间。通常不到一毫秒。

8、Waiting (TTFB)

等待初始响应所用的时间,也称为至第一字节的时间。

  • 可优化部分
    * 服务器响应速度 * 服务器网络带宽

9、Content Download / Downloading

接收响应数据所用的时间。

  • 可优化部分
    * 服务器网络带宽 * 单个文件大小


一、首先网站出现TTFB时长变长

相关截图:

调取慢日志:

Laravel框架一直在打印出现了文件锁

[13-May-2021 11:00:39]  [pool wepaas] pid 98751
script_filename = /ebsig/data/laravel/public/index.php
[0x00007f9fb2e1ee20] fopen() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:54
[0x00007f9fb2e1ed70] sharedGet() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/FileSessionHandler.php:71
[0x00007f9fb2e1ecd0] read() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php:97
[0x00007f9fb2e1ec50] readFromHandler() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php:87
[0x00007f9fb2e1eb80] loadSession() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php:71
[0x00007f9fb2e1eb20] start() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php:102
[0x00007f9fb2e1eab0] Illuminate\Session\Middleware\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Support/helpers.php:1041
[0x00007f9fb2e1ea30] tap() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php:103
[0x00007f9fb2e1e9c0] startSession() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php:57
[0x00007f9fb2e1e890] handle() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
[0x00007f9fb2e1e7c0] Illuminate\Pipeline\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
[0x00007f9fb2e1e700] Illuminate\Routing\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php:37
[0x00007f9fb2e1e630] handle() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
[0x00007f9fb2e1e560] Illuminate\Pipeline\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
[0x00007f9fb2e1e4a0] Illuminate\Routing\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php:66
[0x00007f9fb2e1e370] handle() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
[0x00007f9fb2e1e2a0] Illuminate\Pipeline\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
[0x00007f9fb2e1e1e0] Illuminate\Routing\{closure}() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:104
[0x00007f9fb2e1e160] then() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php:667
[0x00007f9fb2e1e0b0] runRouteWithinStack() /ebsig/data/laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php:642

解决方案:

由于分布式框架原因,应用使用的是共享存储,后面将Laravel框架内的session文件目录调整到服务根目录的tmp下,调整Laravel框架下的config\session.php文件

/*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => '/tmp'

同时也将限流限制去掉

//调整文件app\Http\Kernel.php

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            //'throttle:60,1',  //把这个拿掉
            'bindings',
        ],
    ];

Laravel默认的限流是针对IP,频率为60次/分钟,经过测试发现,如果多个IP属于同一个局域网,比如连接同一个WI-FI,则会判定为同一个IP,进行限流。
也就是说如果同一个局域网下有20人在使用,那么每人刷新3次,就达到了限流标准。 就会返回429 Too Many Requests ,而且是以Laravel默认的错误页面渲染的方式返回,如果不加以处理,在特定场景下无法满足业务需求。

VUE代码优化:

vue-router配置路由 , 使用vue的异步组件技术 , 可以实现按需加载.
但是,这种情况下一个组件生成一个js文件

{ path: '/home', name: 'home', component: resolve => require(['@/components/home'],resolve) },
{ path: '/index', name: 'Index', component: resolve => require(['@/components/index'],resolve) },
{ path: '/about', name: 'about', component: resolve => require(['@/components/about'],resolve) }

解决方案:

删除了无用的路由和一些页面文件,调整路由,确保所有的路由页面都走懒加载的方式。


关于TTFB优化结语:

主要还是因为Session文件存储问题导致的TTFB缓慢,业务的代码这块并不存在耗时的部分,调整了存储目录之后,网站没有再出现TTFB过长问题,但是紧接着出现了Content-download耗时过长问题,平时运行正常的页面,却出现了需要3秒左右的加载时间。


二、解决网站出现ContentDownload过长

相关截图:

问题初步分析:

从截图中可以分析出来,返回的数据包相对较大(330KB),其次也有可能是因为服务端的网络带宽问题引起的传输过慢。于是从服务端和代码层面都做了详细的日志跟踪打印。


应用程序跟踪:

从Laravel框架index入口开始,对于整个请求链路做了耗时打印,由于服务端会对每次请求头追加一个请求ID,HTTP_X_REQUEST_ID,所以有了这个请求ID,就能够对一次请求的完整链路做很好的跟踪。

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/
$starttime = microtime(true);

require __DIR__.'/../bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

require_once __DIR__ . '/../app/Libraries/Login.php';

$handle_files_time = microtime(true)-$starttime;

if ($handle_files_time > 0.5) {
	error_log($_SERVER['REQUEST_URI'].'<br>'.$_SERVER['HTTP_X_REQUEST_ID'].'==require_once文件结束总耗时:' . $handle_files_time);
}


/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$send_starttime = microtime(true);

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$handle_business_time = microtime(true)-$send_starttime;

if ($handle_business_time > 0.5) {
	error_log($_SERVER['REQUEST_URI'].'<br>'.$_SERVER['HTTP_X_REQUEST_ID'].'==response->send耗时:' . $handle_business_time);
}

$terminate_starttime = microtime(true);

$kernel->terminate($request, $response);

$handle_terminate_time = microtime(true)-$terminate_starttime;

if ($handle_terminate_time > 0.5) {
	error_log($_SERVER['REQUEST_URI'].'<br>'.$_SERVER['HTTP_X_REQUEST_ID'].'==kernel->terminate耗时:' . $handle_terminate_time);
}

跟踪结果:

从打印的日志来看,凸显出了两块问题:

1、出现了redis超时问题,正式环境部署的是哨兵模式

2、出现了json_decode超时


服务端方面的优化:

1、解决CDN中的gzip问题
1.1:在CDN上调整gzip的策略
1.2:由于腾讯云只能针对具体文件后缀去压缩,程序这边将需要对返回数据包压缩的ajax接口加.pack后缀,变向实现
2、调整redis,从哨兵模式换成单机模式
3、进行了扩容
3.1:需要部署自动扩容机制

代码方面的优化:

1、由于之前调整了session的存储目录,所以关闭了框架的csrf校验

2、面查询接口返回数据方式调整,将数据包暂存redis,只返回redis的key,PHP再通过key获取数据


关于Content-download优化结语:

在业务代码这块没有什么问题,主要还是周边的一些问题。比如腾讯云的CDN加速不能像Nginx那样可以根据Content-Type做加速,只能通过具体的文件后缀去做加速,基于这样的背景,我们不得不调整返回数据包比较大的接口路由,在Laravel接口路由后面加上了“.pack”后缀,然后把这个后缀加入到CDN加速里面。


三、结束语

经过针对两次性能问题的优化,最终网站响应很稳定,基本上在1秒之内即可完成加载和渲染。现在的网站建设不再像以前那样普通,架构上是分布式,服务器上用到各种云服务,代码层面上前后端分离开发,所以要想解决一个网站的性能问题,得各方面结合起来一起分析排查,这对于解决问题的人员整体素质要求还是有点的,需要掌握前端和后端整体的框架,也需要有足够多的技术基础作为分析问题的支持。

扫描二维码推送至手机访问。

版权声明:本文由AR编程网发布,如需转载请注明出处。

本文链接:http://www.arlanguage.com/post/205.html

标签: nginx访问慢
分享给朋友:

“基于一次ContentDownload变慢而进行的网站性能优化” 的相关文章

如何优化Nginx性能?

优化Nginx性能涉及多个方面,包括配置优化、硬件资源、软件选择和系统监控等。以下是一些常见的Nginx性能优化技巧,以及一些示例代码和配置:优化Nginx配置调整超时时间:调整客户端和服务器之间的超时时间,例如client_header_timeout、client_body_timeout等。设...

nginx限制php程序“跨站”访问 nginx限制只能域名访问

我秀站外合作有一个需求:需在一台web服务器上增加一个虚拟主机用来做图片资源站,所用程序为第三方,担心有后门程序,因此希望最好隔断与原机器其他服务的关系。思考了一下,确实有一些风险存在。目前我们服务器上都统一使用nobody用户启动nginx和php,包括web目录,这些机器上部分有多个域名在一起运...

Nginx路由匹配规则location的小总结

使用过nginx的同学都知道,在nginx配置文件中通过location配置路由转发规则,配置语法为:location [=|~|~*|^~] /uri/ { ... }中括号中为路由匹配符号,常见的有:1 =:精确匹配 2 ^~:精确前缀匹配 3 ~:区分...

Nginx总结(九) 实现系统的动静分离

前段时间,搞Nginx+IIS的负载均衡,想了解的朋友,可以看这篇文章:《nginx 和 IIS 实现负载均衡》,然后也就顺便研究了Nginx + IIS 实现动静分离。所以,一起总结出来,与大家共同探讨。 什么是动静分离所谓系统动静分离,其实,就是将网站静态资源(HTML,JavaScript,C...

为什么一条UPDATE语句有索引反而更慢

先来看看今天要讲的主人翁:UPDATE `i_msg_system` set `deliver`=1 where `uid`=10000 and `msg_group`=0 and `deliver`=0;涉事表结构:CREATE TABLE `i_msg_system` ( `id` int(...

一般人绝对无法发现的nginx锅

nginx热启动:nginx -s reloadPS:要在/etc/profile环境变量PATH里配置nginx的路径。配置完执行 source /etc/profile 让变量生效。 一次部署,同样的前端代码,放到了nginx里面运行,但是有一个模块全部页面都报这个错误,其他模块正常展示。以前遇...