Spring Data JPA 緩衝結合Ehcache介紹,jpaehcache
一級緩衝:
會話session、事務層級的,事務退出,緩衝就失效了。
實體管理器在事務執行期間持有一份資料的拷貝,而非直接操作資料源。
二級緩衝:
進程範圍級或叢集範圍的緩衝,這個層級的緩衝可配置和修改,整個應用程式的生命週期內都可以訪問。
由於多個事務會同時訪問二級緩衝中相同的資料,因此二級緩衝必須提供必要的並發存取原則
以id為標識放到緩衝(針對id)
訪問過程:先一級緩衝、後二級緩衝,再資料來源
橋接第三方緩衝,hibernate二級緩衝的實現:
1.ehcache
2.OScache
3.JBossCache
4.Memcached
......
什麼樣的資料適合二級緩衝呢?
1.很少被修改的資料
2.不是很重要,允許偶爾出現並發的資料
3.不會被高並發訪問的資料
4.參數資料,通常是數量有限,極少被修改,大量的被其它執行個體引用的
不適合使用二級緩衝?
1.經常被修改的資料,代價太大,得不償失
2.金錢敏感的資料,絕對不允許出現並發
3.與其他應用共用的資料
查詢快取:
批量的緩衝、批量的擷取,如按查詢條件、查詢結果進行緩衝;
JPA+Ehcache緩衝配置:
1.加入Ehcache依賴
<!--Ehcache-core 包 --><dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.9</version></dependency> <!--添加Hibernate-Ehcache包 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate-version}</version></dependency>
2.配置ehcache.xml
<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <diskStore path="java.io.tmpdir/ehcache"/> <!-- 預設緩衝 --> <defaultCache maxElementsInMemory="1000" <!-- 預設緩衝中存最多資料項目 --> eternal="false" <!--是否永不到期--> timeToIdleSeconds="120" <!--空閑多長時間後從緩衝中刪除--> timeToLiveSeconds="120" <!--活躍多長時間後從緩衝中刪除--> overflowToDisk="false"/><!--超過maxElementsInMemory之後是否儲存到硬碟--> <!-- 題目緩衝--> <cache name="questionCache" maxElementsInMemory="1000" eternal="true" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" <!--資料項目失效策略--> /></ehcache>
3.persistence.xml配置加入緩衝配置
<prop key="hibernate.cache.use_query_cache">true</prop> <!--開啟查詢快取--><property name="hibernate.cache.use_second_level_cache">true</property><!--開啟二級緩衝--><prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <!--ehcache支援--><property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property><!--ehcache支援--><property name="hibernate.cache.provider_configuration">classpath:ehcache.xml</property><!--ehcache詳細配置-->
4.配置需二級緩衝實體和屬性
在實體類和實體的那些集合屬性上啟用二級緩衝使用
@Entity @Table(name = "user") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE,region="指定的cache")@Cacheable(true) public class User implements java.io.Serializable { private static final long serialVersionUID = 6980093847795726310L; private String id; private String userName; private String password; private Set<Role> roles = new HashSet<Role>(); ....省略 /** *註:如果一個實體需要二級緩衝,若該實體含有<set...>,<list...>等屬性時,也必須要指定緩衝策略。 */ @ManyToMany(fetch = FetchType.LAZY) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) }) public Set<Role> getRoles() { return this.roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }
Usage提供緩衝對象的事務隔離機制有如下幾種:
(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
ehcache不支援transaction事務機制,但其他三種可以使用:
read-only::
無需修改, 那麼就可以對其進行唯讀 緩衝,注意,在此策略下,如果直接修改資料庫,即使能夠看到前台顯示效果,
但是將對象修改至cache中會報error,cache不會發生作用。另:刪除記錄會報錯,因為不能在read-only模式的對象從cache中刪除。
read-write:
需要更新資料,那麼使用讀/寫緩衝 比較合適,前提:資料庫不可以為serializable transaction isolation level(序列化交易隔離等級)
nonstrice-read-write:
只偶爾需要更新資料(也就是說,兩個事務同時更新同一記錄的情況很不常見),也不需要十分嚴格的事務隔離,那麼比較適合使用非嚴格讀/寫緩衝策略。
5.配置查詢快取
a.通過添加@QueryHints來實現查詢快取
public interface DictDao extends JpaRepository<Dict, Integer>,JpaSpecificationExecutor<Dict>{ // spring-data-jpa預設繼承實現的一些方法,實作類別為SimpleJpaRepository。 // 該類中的方法不能通過@QueryHint來實現查詢快取。 @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") }) List<Dict> findAll(); @Query("from Dict") @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") }) List<Dict> findAllCached(); @Query("select t from Dict t where t.name = ?1") @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") }) Dict findDictByName(String name);}
b.自訂Repository擴充介面內使用查詢快取
public class UserReposiotryImpl { @PersistenceContext private EntityManager em; /** * 使用查詢快取,調用setHint方法配置. */ public User findByCustomizeId() { return (User) em.createQuery("from User p where p.id=1") .setHint("org.hibernate.cacheable", true).getSingleResult(); }