本测试代码基于yii2框架、apache服务器,apache、mysql、memcache都装在同一机器。
测试业务内容显示文章列表,如下图:

测试一、直接数据库访问方式,测试代码。
class ListController extends Controller { public $layout = false; public function actionDb() { $specialRecommend = new SpecialRecommend(); $page = empty($_GET['page']) == false ? intval($_GET['page']) : 1; $pageSize = 10; $rows = $specialRecommend->find()->offset(($page - 1) * $pageSize)->limit($pageSize)->orderBy("sid desc")->asArray()->all(); $html = $this->render('index', [ 'rows' => $rows, ]); return $html; } }
压测代码
ab -n 1000 -c 50 "http://testyii.com/index.php?r=list/db&page=1"
压测结果

吞吐率(rps):159.52[#/sec]
测试二、加入缓存,测试代码
public function actionCache() { $page = empty($_GET['page']) == false ? intval($_GET['page']) : 1; $pageSize = 10; $key = "cacke_key"; $data = Yii::$app->cache->get($key); $rows = json_decode($data, true); if(empty($rows) == true){ $specialRecommend = new SpecialRecommend(); $rows = $specialRecommend->find()->offset(($page - 1) * $pageSize)->limit($pageSize)->orderBy("sid desc")->asArray()->all(); Yii::$app->cache->set($key, json_encode($rows)); } $html = $this->render('index', [ 'rows' => $rows, ]); return $html; }
压测代码
ab -n 1000 -c 50 "http://testyii.com/index.php?r=list/cache&page=1"
压测结果

吞吐率(rps):220.66[#/sec]
测试三、开启yii2伪静态,设置apache重定向时先判断目录是否存在,如果存在则直接访问真实目录
.htaccess
Options +FollowSymLinks IndexIgnore */* RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php
测试代码
public function actionFile() { $specialRecommend = new SpecialRecommend(); $page = empty($_GET['page']) == false ? intval($_GET['page']) : 1; $pageSize = 10; $rows = $specialRecommend->find()->offset(($page - 1) * $pageSize)->limit($pageSize)->orderBy("sid desc")->asArray()->all(); $html = $this->render('index', [ 'rows' => $rows, ]); $path = Yii::$app->basePath . "/web/data/list/file/"; if(file_exists($path) == false){ mkdir($path, 0755, true); } $file = $path . "{$page}.html"; file_put_contents($file, $html); return $html; }
压测代码
ab -n 1000 -c 50 "http://testyii.com/data/list/file/1.html"
压测结果

吞吐率(rps):1327.14 [#/sec]
测试三在本地文件存在时,apache直接访问静态文件,不再需要php处理,rps比测试一性能提高接近10倍。