懶人快取實驗

edited 十月 2013 in CakePHP
我實在懶得一個一個查詢去做快取,所以鑽了一下,發現了一個偷吃步的方式...

1. 把 cake/libs/model/datasources/dbo_source.php copy 到 models/datasources/dbo_source.php
2. 加入下面程式碼:
331,336d330
< 	    if(substr($sql, 0, 6) == 'SELECT') {
< 	        $key = md5($sql);
< 	        if($data = Cache::read($key)) {
< 	            return $data;
< 	        }
< 	    }
359,362d352
< 			if(isset($key)) {
< 			    Cache::write($key, $out, 5);
< 			    unset($key);
< 			}
3. 把快取打開 config/core.php
Cache::config('default', array('engine' => 'File', //[required]
									'duration'=> 3600, //[optional]
									'probability'=> 100, //[optional]
 									'prefix' => 'cake_', //[optional]  prefix every cache file with this string
 									'lock' => false, //[optional]  use file locking
 									'serialize' => true, //[optional]
								)
 					);
4. ...好了

為了證明快取真的有用,所以透過 siege -c 100 -r 3 這樣的指令進行測試,結果如下:

使用前:
Transactions: 291 hits
Availability: 97.00 %
Elapsed time: 56.03 secs
Data transferred: 2.18 MB
Response time: 14.61 secs
Transaction rate: 5.19 trans/sec
Throughput: 0.04 MB/sec
Concurrency: 75.88
Successful transactions: 291
Failed transactions: 9
Longest transaction: 29.51
Shortest transaction: 2.72

檔案快取 5 秒:
Transactions: 300 hits
Availability: 100.00 %
Elapsed time: 45.61 secs
Data transferred: 2.25 MB
Response time: 12.66 secs
Transaction rate: 6.58 trans/sec
Throughput: 0.05 MB/sec
Concurrency: 83.29
Successful transactions: 300
Failed transactions: 0
Longest transaction: 25.88
Shortest transaction: 0.81

檔案快取 30 秒:
Transactions: 300 hits
Availability: 100.00 %
Elapsed time: 37.79 secs
Data transferred: 2.25 MB
Response time: 11.26 secs
Transaction rate: 7.94 trans/sec
Throughput: 0.06 MB/sec
Concurrency: 89.43
Successful transactions: 300
Failed transactions: 0
Longest transaction: 20.18
Shortest transaction: 2.37

APC 快取 30 秒:
Transactions: 300 hits
Availability: 100.00 %
Elapsed time: 43.69 secs
Data transferred: 2.25 MB
Response time: 11.59 secs
Transaction rate: 6.87 trans/sec
Throughput: 0.05 MB/sec
Concurrency: 79.61
Successful transactions: 300
Failed transactions: 0
Longest transaction: 19.19
Shortest transaction: 5.24

...怪怪的, APC 怎麼比檔案還慢,然後發現,應該把 serialize 拿掉,結果如下:
Transactions: 300 hits
Availability: 100.00 %
Elapsed time: 34.83 secs
Data transferred: 2.25 MB
Response time: 10.39 secs
Transaction rate: 8.61 trans/sec
Throughput: 0.06 MB/sec
Concurrency: 89.46
Successful transactions: 300
Failed transactions: 0
Longest transaction: 19.44
Shortest transaction: 2.25

感覺比較舒服了,不過建議還是個別查詢進行,...建議啦...

原始討論: http://twpug.net/x/modules/newbb/viewtopic.php?topic_id=3832
Sign In or Register to comment.