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

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值