spring基于注解Ehcache緩存整合

jopen 11年前發布 | 98K 次閱讀 Ehcache Spring JEE框架

    都知道spring已經對Ehcache進行了很好的支持,我的spring版本是3.2.2在spring-context-support.jar包中可以看到.以前的版本可能會不太一樣。

spring基于注解Ehcache緩存整合

我下的ehcache是ehcache-web-2.0.4-distribution.gzehcache-2.7.3-distribution.tar.gz一個做頁面的緩存一個做查詢的緩存。

    echcache的配置也不說了網上一大堆,而且解釋的也很清楚。但是spring基于注解的整合好像還不太一樣,好吧看官方文檔進行配置好一點。

    官網上有這么一句話:EHCache support moved to spring-context-support 看來以前的版本還不是在上面提到的那個包中。接著看配置吧:

    

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    <cache:annotation-driven />
</beans>
這是官方文檔中的基于注解的XML配置如果加上緩存的配置的話上面的配置還要加上下面這一句:
xmlns:p="http://www.springframework.org/schema/p"
緩存的配置如下:


<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
<!-- EhCache library setup -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="classpath:ehcache.xml" p:shared="true"/>

OK!!緩存已經完成了

說明一下官網上沒有p:shared="true"在配echcahe的時候,這時啟動會報一個錯誤:


net.sf.ehcache.CacheException:Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following
我找了半天也不知道起動的時候哪還創建了一個CancheManager但加上 p:shared="true"就沒事了。命名空間的p打不開我也不知道是什么意思。請高手指點。我覺得大概意思就是使用一個cache吧。


做一個簡單的測試!

@Cacheable(value="sampleCache1",key="#id")
public T getById(String id) {
  return (T) getSession().get(clazz, id);
}
在baseDao的get方法上進行配置在測試類中用userService服務進行測試看輸出幾條sql語句:

test類

public class CancheSpring extends BaseSpringTest {
    @Resource
    private UserService userService;

    @Test
    public void testGetCanche(){
        String id = "40288183401e060a01401e06116b0000";
        User user = userService.getById(id);
        System.out.println(user);
        User user2 = userService.getById(id);
        System.out.println(user2);
    }
}
當然id我從數據庫中直接copy出來的UUID.輸出結果如下:

spring基于注解Ehcache緩存整合
OK。很明顯可以看到兩個對象是一模一樣的。好吧配置成功能了可以在其他需要的地方方便使用。還有一個注解是@CacheEvict是刪除操作。 



 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!