spring缓存cache的使用

在spring配置文件中添加schema和spring对缓存注解的支持:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache.xsd"
       default-autowire="byName">

    <!--缓存配置-->
    <cache:annotation-driven/>

在spring配置文件中加入缓存管理器 :

    <!-- generic cache manager -->
    <bean id="cacheManager"
          class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                      p:name="hardwareCache"/>

                      <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" 
                      p:name="bannerCache"/>
            </set>
        </property>
    </bean>

然后在代码的service的impl层加上如下注解即可把数据缓存起来:

@Cacheable(value="bannerCache")

其中@Cacheable表示spring将缓存该方法获取到的数据,(缓存是基于key-value方式实现的),key为该方法的参数,value为返回的数据,当你连续访问该方法时你会发现只有第一次会访问数据库. 其他次数只是查询缓存.减轻了数据库的压力.
这里写图片描述
当更新了数据库的数据,需要让缓存失效时,使用下面的注解:
这个注解表示让appCache缓存的所有数据都失效.

@CacheEvict(value = "appCache", allEntries = true)

这里写图片描述

更详细配置介绍可看
http://tom-seed.iteye.com/blog/2104430

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值