Spring中@Cacheable的用法

在Spring中通过获取MemCachedClient来实现与memcached服务器进行数据读取的方式。不过,在实际开发中,我们往往是通过Spring的@Cacheable来实现数据的缓存的,所以,本文给大家详细介绍一下@Cacheable的用法。首先,在使用@Cacheable之前,我们要做好准备工作。

第一步:要导入相应的jar包。
   <classpathentry kind="lib" path="lib/spring-core-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-cache-1.0.10.jar"/>
    <classpathentry kind="lib" path="lib/spring-context-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-beans-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/commons-logging-1.2.jar"/>
    <classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
    <classpathentry kind="lib" path="lib/spring-expression-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/java_memcached-release_2.0.1.jar"/>
    <classpathentry kind="lib" path="lib/spring-aop-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-aspects-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-context-support-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-tx-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/aopalliance-1.0.jar"/>
    <classpathentry kind="lib" path="lib/ognl-3.0.6.jar"/>
    <classpathentry kind="lib" path="lib/trafficCounter-1.0.2.jar"/>
    <classpathentry kind="lib" path="lib/aspectjweaver-1.8.4.jar"/>
    <classpathentry kind="lib" path="lib/javassist-3.11.0.GA.jar"/>

第二步:xml文件中增加命名空间。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    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/tx
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

第三步:添加自动扫描功能。

<context:component-scan base-package="service" />
<aop:config proxy-target-class="true"/>

第四步:增加缓存管理类。

<bean id="memCacheProvider" class="com.springcache.memcache.MemCacheProvider">
        <property name="memCache" ref="memCacheClient"/>
</bean>
<bean id="cacheManager" class="com.springcache.CacheManager">
        <property name="elParserName" value="ognl"/>
        <property name="cacheProviders">
        <map>
        <entry key="remote" value-ref="memCacheProvider"></entry>
        </map>
        </property>
</bean>

第五步:建立一个测试类。

package service;
import org.springframework.stereotype.Service;
import com.springcache.annotation.Cacheable;
@Service
@Cacheable
public class MemcachedService {
    @Cacheable(name = "remote", key = "‘USER_NAME_‘+#args[0]", expire = 60 )
    public String storeUserName(String accountId, String name)
    {
        return name;
    }
    @Cacheable(name = "remote", expire = 60)
    public String storeUserAddress(String accountId, String address)
    {
        return address;
    }
}

@Cacheable支持如下几个参数:
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL。例如:memCachedService.storeUserAddress("user", "BeiJing");
        所以对应的key为:service.MemcachedService-storeUserAddress_user_BeiJing
name:存储位置。在本来中remote表示使用memcached服务器。
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL。
expire:过期时间,单位为秒。

第六 扩展:使用Spring4.3解决缓存过期后多线程并发访问数据库的问题

缓存过期之后,如果多个线程同时请求对某个数据的访问,会同时去到数据库,导致数据库瞬间负荷增高。Spring4.3为@Cacheable注解提供了一个新的参数“sync”(boolean类型,缺省为false),

当设置它为true时,只有一个线程的请求会去到数据库,其他线程都会等待直到缓存可用。这个设置可以减少对数据库的瞬间并发访问。

不过不一定所有的缓存系统都支持这个配置。经过验证,Guava Cache是支持的  参考:http://blog.csdn.net/clementad/article/details/51250472

@Service
public class UserServiceCacheablesImpl implements UserServiceCacheables{
    private final static Logger logger = LoggerFactory.getLogger(UserServiceCacheablesImpl.class);  

    @Autowired
    UserDAO userDAO;  

    @Override
    @Cacheable(value="getPhoneNoByUserId", sync=true) 
    public String getPhoneNoByUserId(int userId) {
        logger.debug("getting data from database, userId={}", userId);
        return userDAO.getPhoneNoByUserId(userId);
    }
}  

最后总结一下:当执行到一个被@Cacheable注解的方法时,Spring首先检查condition条件是否满足,如果不满足,执行方法,返回;如果满足,在name所命名的缓存空间中查找使用key存储的对象,如果找到,将找到的结果返回,如果没有找到执行方法,将方法的返回值以key-value对象的方式存入name缓存中,然后方法返回。

时间: 2024-08-27 10:54:11

Spring中@Cacheable的用法的相关文章

Spring中HibernateCallback的用法(转)

Hibernate的复杂用法HibernateCallback HibernateTemplate还提供一种更加灵活的方式来操作数据库,通过这种方式可以完全使用Hibernate的操作方式.HibernateTemplate的灵活访问方式是通过如下两个方法完成: q      Object execute(HibernateCallback action) q      List execute(HibernateCallback action) 这两个方法都需要一个HibernateCallb

Spring中jdbcTemplate的用法实例

一.首先配置JdbcTemplate: 要使用Jdbctemplate 对象来完成jdbc 操作.通常情况下,有三种种方式得到JdbcTemplate 对象.       第一种方式:我们可以在自己定义的DAO 实现类中注入一个DataSource 引用来完 成JdbcTemplate 的实例化.也就是它是从外部"注入" DataSource 到DAO 中,然后 自己实例化JdbcTemplate,然后将DataSource 设置到JdbcTemplate 对象中.       第二种

spring 中StoredProcedure的用法--转载

StoredProcedure是一个抽象类,必须写一个子类来继承它,这个类是用来简化JDBCTemplate执行存储过程操作的. 首先我们写一个实现类: package com.huaye.framework.dao; import java.sql.Types; import java.util.HashMap; import java.util.Map; import org.springframework.jdbc.core.RowMapper; import org.springfram

spring 中spel 的用法

spel :spring表达式语言 简称(spel)是一个支持运行时查询和操作对象图的强大表达式语言 语法类似el :spel使用 #{...}作为定界符,所有在大括号中的字符都将被认为是spel spel 为bean的属性进行动态赋值提供了便利 通过spel可以实现 a.通过bean'的id对bean进行引用 b.调用方法以及引用对象中的属性 c.计算表达式的值 d.正则表达式的匹配 下面做个小测试 4. xml中的配置 <?xml version="1.0" encoding

Spring中ApplicationContextAware的用法

详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt379 一.这个接口有什么用? 当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean.换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象. 二.怎么用? 举个例子吧: 例如我有一个方法类AppUtil,这个方法类中需要使用到的Application

Spring 中classPath:用法

参考文章地址: http://hi.baidu.com/huahua035/item/ac8a27a994b55bad29ce9d39 http://blog.csdn.net/lushuaiyin/article/details/6880640 http://jeiofw.blog.51cto.com/3319919/934413 classpath就是代表  /WEB-INF /classes/  这个路径(如果不理解该路径,就把一个web工程发布为war包,然后用winrar查看其包内路径

spring 中 @import的用法

第一步: 新建Java工程    FirstSpringJAVA 第二步:导入相关的spring jar包 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency

spring中autowire的用法

Autowire模式就是在spring的声明文件里用作进行对象间的关联关系自动绑定的,就是在spring beanfactory内的一个bean对其bean的引用可以自动进行,而不一定用ref=的方式显式声明.在reference的3.3.6节有详细的介绍,autowire主要有5种模式: 1 no 不使用Autowire,引用关系显示声明,spring的reference也建议不用autoware,因为这会破坏模块关系的可读性,原文如下: Note: as has already been m

Spring中@Async用法总结

 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在spring 3.x之后,就已经内置了@Async来完美解决这个问题,本文将完成介绍@Async的用法. 1.  何为异步调用? 在解释异步调用之前,我们先来看同步调用的定义:同步就是整个处理过程顺序执行,当各个过程都执行完毕,并返回结果. 异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕:而是继续