SQLAlchemy支持缓存吗?

38

SQLAlchemy是否支持某种缓存机制,以便如果我重复运行相同的查询,它将从缓存中返回响应,而不是查询数据库?这个缓存是否在更新数据库时自动清除?

或者,在一个CherryPy + SQLAlchemy设置中实现这个功能的最佳方法是什么?

4个回答

56
我们拥有一个相当全面的缓存解决方案,例如与嵌入式钩子一起在0.6中使用。它是一个基于Query子类化、使其意识到Beaker,并通过查询选项控制显式查询以及惰性加载器的查询缓存的方法。
我现在正在生产环境中运行它。示例本身位于dist中,介绍文档位于http://www.sqlalchemy.org/docs/orm/examples.html#beaker-caching
更新:Beaker现已被替换为dogpile缓存: http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.dogpile_caching

18

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


缓存结果集不使用Identity Map吗?我第一次在这个上下文中听说了Dogpile。或者它与Identity Map有什么关系吗? - Susa

18

虽然不是回答你的第二个问题,但该链接中的评论表明SQLAlchemy不支持缓存:http://spyced.blogspot.com/2007/01/why-sqlalchemy-impresses-me.html

Raven说:

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/sqlalchemy@googlegroups.com/msg15667.html 表明/显示,后续的查询不使用查询语句,而是从标识映射中返回实例,但这仅在您使用主键进行查询时有效。 - andho

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接