Hız ve ölçeklenebilirlik için Kohana-tabanlı Web Siteleri optimize

6 Cevap php

Ben Kohana ile inşa edilmiş bir site beni bir adım geri almak ve bazı tasarım değerlendirmek için neden, dün trafik büyük bir miktar çarptı. Ben Kohana tabanlı uygulamaları optimize etmek için bazı standart teknikler nelerdir merak ediyorum?

Ben de kıyaslama ilgileniyorum. Amacıyla tüm sayfalar için yürütme kez görmek için her kontrolör-yöntem için kurulum Benchmark::start() ve Benchmark::stop() gerekiyor, yoksa küresel ve hızlı bir şekilde kıyaslama uygulamak mümkün duyuyorum musunuz?

Ben gelecek zamanda daha Cache-kitaplığı kullanıyor olacak, ama ben şu anda sadece farkında değilim bunu yapabilir çok şey var eminim ben daha önerilere açığım.

6 Cevap

What I will say in this answer is not specific to Kohana, and can probably apply to lots of PHP projects.

Here are some points that come to my mind when talking about performance, scalability, PHP, ...
I've used many of those ideas while working on several projects -- and they helped; so they could probably help here too.


First of all, when it comes to performances, there are many aspects/questions that are to consider:

  • Sunucunun yapılandırma {[(0)];} Eğer ServerFault hakkında daha fazla olduğu yardım alabilirsiniz, sanırım,
  • PHP kodu,
  • Veritabanı sorguları,
  • Lütfen web sunucusu kullanıyorsanız ya da değil?
  • Eğer önbelleğe alma mekanizmasının her türlü kullanabilir miyim? Yoksa her zaman ihtiyacım var daha o web sitesinde güncel veri?


Using a reverse proxy

Gerçekten yararlı olabilecek ilk şey gerçekten PHP / MySQL hesaplamalar {[(3) ihtiyaç varnish , in front of your webserver: let it cache as many things as possible, bu yüzden sadece istekleri gibi, bir reverse proxy kullanıyor }] Apache / PHP / MySQL bunu yapmak.

  • First of all, your CSS/Javascript/Images -- well, everything that is static -- probably don't need to be always served by Apache
    • Yani, ters proxy önbelleğe tüm bu olabilir.
    • Bu statik dosyalara hizmet Apache için büyük bir olay olduğunu, ama daha az o bu iş için vardır, daha fazla PHP ile yapmak mümkün olacak.
    • Unutmayın: Apache bir anda yalnızca sunucu isteklerini bir, sonlu sınırlı sayıda yapabilirsiniz.
  • Then, have the reverse proxy serve as many PHP-pages as possible from cache: there are probably some pages that don't change that often, and could be served from cache. Instead of using some PHP-based cache, why not let another, lighter, server serve those (and fetch them from the PHP server from time to time, so they are always almost up to date)?
    • Örneğin, very often, birkaç dakika boyunca önbellekte onlara sahip Apache + PHP + MySQL istek yüzlerce / binlerce kurtarabilecek istenen bazı RSS beslemeleri (We generally tend to forget those, when trying to optimize for performances) varsa!
    • Onlar (example: homepage?) dakika en azından birkaç değişiklik yoksa, sitenizin en çok ziyaret edilen sayfalar için aynı, o zaman, CPU atık gerek onlara her zaman yeniden üreten bir kullanıcı bunları ister.
  • Maybe there is a difference between pages served for anonymous users (the same page for all anonymous users) and pages served for identified users ("Hello Mr X, you have new messages", for instance)?
    • Eğer öyleyse, muhtemelen anonim kullanıcılar için sunulan sayfayı önbelleğe ters proxy yapılandırabilirsiniz (based on a cookie, like the session cookie, typically)
    • - Kullanıcıların sadece küçük bir parçası olabilir, sadece tanımlanan kullanıcılar: Apache + PHP ile başa çıkmak için daha az olduğu anlamına edeceğiz.

About using a reverse-proxy as cache, for a PHP application, you can, for instance, take a look at Benchmark Results Show 400%-700% Increase In Server Capabilities with APC and Squid Cache.
(Yep, they are using Squid, and I was talking about varnish -- that's just another possibility ^^ Varnish being more recent, but more dedicated to caching)

If you do that well enough, and manage to stop re-generating too many pages again and again, maybe you won't even have to optimize any of your code ;-)
At least, maybe not in any kind of rush... And it's always better to perform optimizations when you are not under too much presure...


As a sidenote: you are saying in the OP:

A site I built with Kohana was slammed with an enormous amount of traffic yesterday,

Bu sudden situation where a reverse-proxy can literally save the day türüdür, web sitenizin, ikinci tarihe kadar değil varlık ile başa çıkabilirim:

  • install it, configure it, let it always -- every normal day -- run:
    • , Bu önbellek PHP sayfaları tutmak için yapılandırma ya da sadece kısa bir süre için; Bu şekilde, her zaman var görüntülenen güncel veriler
  • And, the day you take a slashdot or digg effect:
    • Önbellek PHP sayfaları tutmak için ters proxy yapılandırma; ya da daha uzun bir süre boyunca; belki Sayfalarınız ikinci bugüne kadar olmayacak, ancak sizin web digg etkiye hayatta sağlayacak!

O konuda, How can I detect and survive being “Slashdotted”? ilginç bir okuma olabilir.


On the PHP side of things:

First of all: are you using a recent version of PHP? There are regularly improvements in speed, with new versions ;-)
For instance, take a look at Benchmark of PHP Branches 3.0 through 5.3-CVS.

Note that performances is quite a good reason to use PHP 5.3 (I've made some benchmarks (in french), and results are great)...
Another pretty good reason being, of course, that PHP 5.2 has reached its end of life, and is not maintained anymore!

Are you using any opcode cache?

  • I'm thinking about APC - Alternative PHP Cache, for instance (pecl, manual), which is the solution I've seen used the most -- and that is used on all servers on which I've worked.
  • Bu gerçekten bir sunucu bir çok CPU yükü azaltmak, bazı durumlarda (I've seen CPU-load on some servers go from 80% to 40%, just by installing APC and activating it's opcode-cache functionality!) olabilir
  • Basically, execution of a PHP script goes in two steps:
    • Opcodes için PHP kaynak kodunun derleme (kind of an equivalent of JAVA's bytecode)
    • Bu opcodes Yürütme
    • APC bellekte bu tutar, yani bir PHP komut dosyası / dosya çalıştırıldığında her zaman yapılması gereken daha az iş var: Sadece RAM opcodes getir ve onları yürütmek.
  • You might need to take a look at APC's configuration options, btw
    • Orada bu oldukça azdır ve bazıları sizin için kullanım hem hız / CPU yük / kolaylığı üzerinde büyük bir etkisi olabilir
    • Örneğin, [apc.stat](http://php.net/manual/en/apc.configuration.php#ini.apc.stat) sistem yükü için iyi olabilir devre dışı bırakma; ama sen bütün opcode-önbelleğini temizlemek sürece PHP dosyalarında yapılan değişiklikler dikkate olmayacak anlamına gelir; Bu konuda, daha fazla bilgi için, bakınız örneğin To stat() Or Not To stat()?


Using cache for data

Mümkün olduğunca, bu avoid doing the same thing over and over again daha iyidir.

The main thing I'm thinking about is, of course, SQL Queries: many of your pages probably do the same queries, and the results of some of those is probably almost always the same... Which means lots of "useless" queries made to the database, which has to spend time serving the same data over and over again.
Of course, this is true for other stuff, like Web Services calls, fetching information from other websites, heavy calculations, ...

Tanımlamak için çok ilginç olabilir:

  • Birçok kez çalıştırmak hangi sorgular, hep aynı veri döndürme
  • Diğer (heavy) hesaplamalar hep aynı sonucu dönen, çok zaman yapılır Hangi

Ve önbellek çeşit bu veriler / sonuçlarını saklamak, bu yüzden onlar için daha kolay - faster - ve "hiçbir şey" için SQL sunucusuna gitmek zorunda değilsiniz.

Büyük önbelleğe alma mekanizmaları vardır, örneğin:

  • APC: Ben daha önce konuştuğumuz opcode cache ek olarak, bu bellek veri depolamak için izin verir
  • Ve / ya da memcached (see also) , which is very useful if you literally have lots veri ve / veya olan using multiple servers, bu gibi dağıtılır.
  • tabii ki, dosyalar hakkında düşünebilirsiniz; ve muhtemelen birçok diğer fikirler.

Ben framework bazı önbellek ile ilgili şeyler geliyor eminim; Eğer "I will be using the Cache-library more in time to come" OP dediğim gibi muhtemelen zaten, biliyorum ;-)


Profiling

En azından, varsa herhangi bir işlevi - genellikle oldukça kolay zayıf noktalar bir çift bulmak için sağlar: Şimdi, yapılacak güzel bir şey Xdebug extension to profile your application kullanmak olacaktır Bu çok zaman alır.

Configured properly , bu gibi bazı grafik araçları ile analiz edilebilir dosyaları profilleme üretecektir:

  • KCachegrind : benim en sevdiğim, ama sadece Linux / KDE üzerinde çalışır
  • Pencereler için Wincachegrind ; Bu KCacheGrind biraz daha az malzeme, maalesef yok - genelde, callgraphs görüntüler değil.
  • Webgrind bu yüzden her yerde çalışır, bir PHP web sunucusu üzerinde çalışan hangi - ama muhtemelen daha az özelliklere sahiptir.

Örneğin, burada KCacheGrind bir çift ekran vardır:

KCacheGrind : main screen KCacheGrind : Callgraph exported as an image

(BTW, the callgraph presented on the second screenshot is typically something neither WinCacheGrind nor Webgrind can do, if I remember correctly ^^ )


(Thanks @Mikushi for the comment) Another possibility that I haven't used much is the the xhprof extension : it also helps with profiling, can generate callgraphs -- but is lighter than Xdebug, which mean you should be able to install it on a production server.

Verilerin görselleştirilmesi için yardımcı olacak, XHGui alonside kullanmak gerekir.


On the SQL side of things:

Şimdi PHP hakkında biraz konuştum o, o more than possible that your bottleneck isn't the PHP-side of things olduğunu unutmayın, ancak veritabanı bir ...

Burada en az iki veya üç şey:

  • You should determine:
    • Uygulama yapıyor en sık yapılan sorgular nelerdir
    • Whether those are optimized (using the right indexes, mainly?), using the EXPLAIN instruction, if you are using MySQL
    • Bu sorguları bazı önbelleğe olabilir mi (see what I said earlier)
  • Is your MySQL well configured? I don't know much about that, but there are some configuration options that might have some impact.

Yine de, en önemli iki şey vardır:

  • Eğer gerek yoksa DB gitmeyin: cache as much as you can!
  • Eğer DB gitmek zorunda olduğunda, verimli sorguları kullanın: kullanım indeksleri; ve profil!


And what now?

Hala okuma varsa, başka ne optimize edilebilir?

Peki, iyileştirmeler için oda hala var ... mimarlık odaklı fikirlerin bir çift olabilir:

  • Switch to an n-tier architecture:
    • Başka bir sunucu üzerinde MySQL koymak (2-tier: one for PHP; the other for MySQL)
    • Birçok PHP sunucuları kullanın (and load-balance the users between those)
    • Use another machines for static files, with a lighter webserver, like:
    • Bunların önünde MySQL için çeşitli sunucuları, PHP için çeşitli sunucuları, ve birkaç ters yakınlık kullanın
    • Tabii ki ücretsiz RAM herhangi bir miktarda olursa olsun, sunucu üzerinde memcached cinleri yükleyin ve / mantıklı olabilir kadar önbelleğe için bunları kullanın.
  • Use something "more efficient" that Apache?
    • I hear more and more often about nginx, which is supposed to be great when it comes to PHP and high-volume websites; I've never used it myself, but you might find some interesting articles about it on the net;

Well, maybe some of those ideas are a bit overkill in your situation ^^
But, still... Why not study them a bit, just in case ? ;-)


And what about Kohana?

Your initial question was about optimizing an application that uses Kohana... Well, I've posted some ideas that are true for any PHP application... Which means they are true for Kohana too ;-)
(Even if not specific to it ^^)

I said: use cache; Kohana seems to support some caching stuff (You talked about it yourself, so nothing new here...)
If there is anything that can be done quickly, try it ;-)

I also said you shouldn't do anything that's not necessary; is there anything enabled by default in Kohana that you don't need?
Browsing the net, it seems there is at least something about XSS filtering; do you need that?

Yine, burada yararlı olabilir bağlantıların bir çift:


Conclusion?

Ve, sonuçlandırmak için, basit bir düşünce:

  • Ne kadar 5 gün ödeme için şirket mal olacak? -- considering it is a reasonable amount of time to do some great optimizations
  • Ne kadar (pay for?) ikinci bir sunucu ve onun bakım satın almak için şirket mal olacak?
  • What if you have to scale larger?
    • Ne kadar 10 gün geçirmek için mal olacak? Daha fazla? uygulamanızın mümkün olan her bit optimize?
    • Ve ne kadar bir çift daha sunucular için?

I'm not saying you shouldn't optimize: you definitely should!
But go for "quick" optimizations that will get you big rewards first: using some opcode cache might help you get between 10 and 50 percent off your server's CPU-load... And it takes only a couple of minutes to set up ;-) On the other side, spending 3 days for 2 percent...

Oh, and, btw: before doing anything: put some monitoring stuff in place, so you know what improvements have been made, and how!
Without monitoring, you will have no idea of the effect of what you did... Not even if it's a real optimization or not!

For instance, you could use something like RRDtool + cacti.
And showing your boss some nice graphics with a 40% CPU-load drop is always great ;-)


Anyway, and to really conclude: have fun!
(Yes, optimizing is fun!)
(Ergh, I didn't think I would write that much... Hope at least some parts of this are useful... And I should remember this answer: might be useful some other times...)

XDebug ve WinCacheGrind veya WebCacheGrind yavaş kod yürütülmesine profil ve analiz etmek için kullanın.

WebCacheGrind WinCacheGrind

Ile Profil kod XDebug.

Önbelleğe bir sürü kullanın. Sayfalarınız görece statik iseniz, o zaman ters proxy bunu yapmak için en iyi yol olabilir.

Kohana veritabanı nesnelerinin kullanılması haricinde, çok çok hızlı bir kutunun dışında. Alıntı Zombor "Sen yerine sonuç dizileri veritabanı sonuç nesne kullanarak vererek, bellek kullanımını azaltabilir." Bu çarptı olan bir sitede bir Hugee performans fark yaratıyor. Daha fazla bellek kullanır kalmaz, bu komut yürütme yavaşlatır.

Ayrıca - önbelleğe kullanmanız gerekir. Ben memcache tercih ve benim gibi bu modelleri kullanabilirsiniz:

public function get($e_id)
{
	$event_data = $this->cache->get('event_get_'.$e_id.Kohana::config('config.site_domain'));

	if ($event_data === NULL)
	{
		$this->db_slave
			->select('e_id,e_name')
			->from('Events')
			->where('e_id', $e_id);

		$result = $this->db_slave->get();
		$event_data = ($result->count() ==1)? $result->current() : FALSE;

		$this->cache->set('event_get_'.$e_id.Kohana::config('config.site_domain'), $event_data, NULL, 300); // 5 minutes
	}

	return $event_data;
}

Bu da önemli ölçüde performans artacaktır. Yukarıdaki iki teknik% 80 oranında bir site performansı geliştirilmiş.

Eğer tıkanıklık olduğunu düşünüyorum nerede hakkında biraz daha bilgi verdi, ben bazı iyi fikirler verebilir eminim.

Ayrıca bazı diğer performans ipuçları için (google) YSlow check out.

Kohana (muhtemelen bu yapılır, ya da değil) kesinlikle ilgili:

Üretim modunda:

  1. (Bu sadece :: find_file sonuçları Kohana önbelleğe, ama bu aslında çok yardımcı olabilir dahili önbelleğe etkinleştirin.
  2. Profiler devre dışı

Sadece benim 2 sent :)

Ben tamamen XDebug ve önbelleğe alma cevapları katılıyorum. Sizin en büyük hız ve ölçek darboğazları tespit ettik kadar optimizasyonu için Kohana tabakası içine bakmayın.

XDebug size zaman harcamak en edildi söylemek ve kodunuzda 'noktaları' belirleyecektir. Eğer performans iyileştirmeleri bazal ve ölçmek böylece bu profil bilgileri tutmak.

Example problem and solution: If you find that you're building up expensive objects from the database each time, that don't really change often, then you can look at caching them with memcached or another mechanism. All of these performance fixes take time and add complexity to your system, so be sure of your bottlenecks before you start fixing them.