2008-10-15 111 views
21

是否SQLAlchemy的支持某種類型的緩存,所以如果我反覆運行,將會返回從緩存中,而不是查詢數據庫的響應相同的查詢?當數據庫更新時,該緩存是否自動清除?SQLAlchemy是否支持緩存?

或者在CherryPy + SQLAlchemy安裝程序上實現此目的的最佳方法是什麼?

回答

41

我們有一個非常全面的緩存解決方案,結合嵌入式掛鉤爲例,在0.6 。這是一個配置子類查詢,讓它知道Beaker的方法,並允許通過查詢選項控制顯式查詢的查詢緩存以及懶惰加載器。

我正在生產中運行它。該示例本身位於dist中,介紹文檔位於http://www.sqlalchemy.org/docs/orm/examples.html#beaker-caching

UPDATE:燒杯現已替換爲dogpile緩存:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching

14

不回答你的第二個問題,但在這個環節上的評論表明,SQLAlchemy的不支持cacheing:http://spyced.blogspot.com/2007/01/why-sqlalchemy-impresses-me.html

烏鴉說...

Does SQLAlchemy do any kind of internal caching? 

For example, if you ask for the same data twice (or an obvious subset 
of the initially requested data) will the database be hit once or twice? 

I recently wrote a caching database abstraction layer for an 
application and (while fun) it was a fair bit of work to get it to a 
minimally functional state. If SQLAlchemy did that I would seriously 
consider jumping on the bandwagon. 

I've found things in the docs that imply something like this might be 
going on, but nothing explicit. 
4:36 PM 

Jonathan Ellis說...

No; the author of SA [rightly, IMO] considers caching a separate concern. 

What you saw in the docs is probably the SA identity map, which makes it so 
if you load an instance in two different places, they will refer 
to the same object. But the database will still be queried twice, so it is 
not a cache in the sense you mean. 
+2

此鏈接http://www.mail-archive.com/[email protected]/msg15667.html提示/顯示,後續查詢不使用查詢,但從身份映射返回實例,但這僅適用於使用主鍵查詢的情況。 – andho 2009-10-06 16:38:57

-4

不,但您可以使用memcache進行緩存。

3

的SQLAlchemy支持兩種類型的緩存:

  1. 緩存結果集,這樣反覆運行相同的查詢命中緩存而不是數據庫。它採用dogpile,支持多種不同的後端,包括memcachedredis和基本平面文件。

    文檔是在這裏:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching

  2. 緩存query對象,以便Python解釋器不必手動每次重新組裝的查詢字符串。這些查詢被稱爲baked queries和高速緩存被稱爲baked。基本上它會緩存所有的動作sqlalchemy在進入數據庫之前 - 它不會減少數據庫調用。最初的基準測試顯示,代碼冗長度稍微增加的代價在query世代時間內加速了40%。

    文檔是在這裏:http://docs.sqlalchemy.org/en/latest/orm/extensions/baked.html