spring基于注解Ehcache缓存整合

    都知道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配置如果加上缓存的配置的话上面的配置还要加上下面这一句:

1 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的时候,这时启动会报一个错误:

1 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是删除操作。

猜你喜欢

转载自zzc1684.iteye.com/blog/2100420