Hibernate缓存机制

首先看一下cache和buffer的区别

The terms "buffer" and "cache" tend to be used interchangeably; note however they represent different things. A buffer is used traditionally as an intermediate temporary store for data between a fast and a slow entity. As one party would have to wait for the other affecting performance, the buffer alleviates this by allowing entire blocks of data to move at once rather then in small chunks. The data is written and read only once from the buffer. Furthermore, the buffers are visible to at least one party which is aware of it.

A cache on the other hand by definition is hidden and neither party is aware that caching occurs.It as well improves performance but does that by allowing the same data to be read multiple times in a fast fashion.

Hibernate的一级缓存和二级缓存均位于持久化层,均用于存放数据库数据的副本。当Hibernate访问数据对象的时候,首先从Session一级缓存中查;查不到,如果配置了二级缓存,那么从二级缓存中查;查不到,再查询数据库,把结果按照ID放入到缓存。

1、一级缓存

事务范围的缓存。只能被当前事务访问,每个事务都有各自独立的缓存,事务结束之时,便是缓存生命终了之时。

事务级别的缓存使用内存作为存储介质。

Hibernate的Session就是一种缓存,我们通常将之称为Hibernate的一级缓存,当想使用session从数据库中查询出一个对象时,Session也是先从自己内部查看是否存在这个对象,存在则直接返回,不存在才去访问数据库,并将查询的结果保存在自己内部。

Hibernate默认开启一级缓存,我们基本可以忽视一级缓存的存在。 其目的主要是为了减少一个事务内的sql查询次数,例如一个对象在同一个事务中被修改了多次,Hibernate将只生成一个包含所有修改的update sql语句。

2、二级缓存

应用范围的缓存。被应用范围的所有事务共享,只有当应用结束的时候(比如Tomcat重启),缓存的生命周期才能结束。

应用范围的缓存可以使用内存或者硬盘作为存储介质。

有可能存在多个事务并发访问缓存的情况,因此必须对缓存采取必要的事务隔离机制。

二级缓存的实现需要通过配置Hibernate的二级缓存插件完成。

二级缓存与SessionFactory关联

2.1 并发访问策略

事务型:并发性能最低,事务隔离级别最高

读写型

非严格读写型

只读型:并发性最好,事务隔离级别最低

2.2 适用二级缓存的情况

数据更新频率低,也就是很少被修改的数据

允许并发访问的非重要数据。如果有些数据绝对不允许出现并发访问的情况,则不适用二级缓存(如财务数据)。

常亮数据

2.3 二级缓存插件

EHCache:与Spring完美结合,具体使用方法参见另外一篇博文(Spring中使用Cache

OSCache

SwarmCache

JBossCache

参考文献

《大型门户网站是这样炼成的》

 

posted @ 2015-10-09 23:34  mingziday  阅读(150)  评论(0编辑  收藏  举报