如果考慮到效能的問題,當從資料庫中擷取資料出來時,您會想到撈出來的資料是不是可以重複使用,不用每一次都連接資料庫進行查詢。
Acegi可以使用User Cache,當AuthenticationProvider需要使用者資料時,先行至User Cache中尋找是否有符合的項目,有的話就直接取回比對,沒有的話,再從資料庫或其它資料來源取得,這可以修改 第一個Acegi 程式 - 改用資料庫作為驗證來源 作為示範,只要修改一下daoAuthenticationProvider 的設定,並加入User Cache即可:
...
<bean id="daoAuthenticationProvider"
class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="jdbcDaoImpl"/>
<property name="userCache" ref="userCache"/>
</bean>
<bean id="jdbcDaoImpl" class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="userCache" class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
<property name="cache">
<bean
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<bean
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
/>
</property>
<property name="cacheName" value="userCache" />
</bean>
</property>
</bean>
...
現在您可以重新啟動程式,當查詢到使用者資料時,會將之放入快取,之後若有相同的查詢,會先至快取中查詢有無資料。
由於使用了EhCache,所以別忘了加入ehcache-*.jar與相依的commons-collections-*.jar。