Spring Cache简介和使用

详解jetcache缓存 阅读详情

Spring Cache

缓存是实际工作中非常常用的一种提高性能的方法, 我们会在许多场景下来使用缓存。

本文通过一个简单的例子进行展开,通过对比我们原来的自定义缓存和 spring 的基于注释的 cache 配置方法,展现了 spring cache 的强大之处,然后介绍了其基本的原理,扩展点和使用场景的限制。通过阅读本文,你应该可以短时间内掌握 spring 带来的强大缓存技术,在很少的配置下即可给既有代码提供缓存能力。

概述

Spring 3.1 引入了激动人心的基于注释(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(例如EHCache 或者 OSCache),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。

Spring 的缓存技术还具备相当的灵活性,不仅能够使用 SpEL(Spring Expression Language)来定义缓存的 key 和各种 condition,还提供开箱即用的缓存临时存储方案,也支持和主流的专业缓存例如 EHCache 集成。

其特点总结如下:

  • 通过少量的配置 annotation 注释即可使得既有代码支持缓存
  • 支持开箱即用 Out-Of-The-Box,即不用安装和部署额外第三方组件即可使用缓存
  • 支持 Spring Express Language,能使用对象的任何属性或者方法来定义缓存的 key 和 condition
  • 支持 AspectJ,并通过其实现任何方法的缓存支持
  • 支持自定义 key 和自定义缓存管理者,具有相当的灵活性和扩展性

本文将针对上述特点对 Spring cache 进行详细的介绍,主要通过一个简单的例子和原理介绍展开,然后我们将一起看一个比较实际的缓存例子,最后会介绍 spring cache 的使用限制和注意事项。好吧,让我们开始吧

我们以前如何自己实现缓存的呢

这里先展示一个完全自定义的缓存实现,即不用任何第三方的组件来实现某种对象的内存缓存。

场景如下:

对一个账号查询方法做缓存,以账号名称为 key,账号对象为 value,当以相同的账号名称查询账号的时候,直接从缓存中返回结果,否则更新缓存。账号查询服务还支持 reload 缓存(即清空缓存)

首先定义一个实体类:账号类,具备基本的 id 和 name 属性,且具备 getter 和 setter 方法

public class Account {

    private int id;
    private String name;

    public Account(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

然后定义一个缓存管理器,这个管理器负责实现缓存逻辑,支持对象的增加、修改和删除,支持值对象的泛型。如下:

import com.google.common.collect.Maps;

import java.util.Map;

/**
 * @author wenchao.ren
 *         2015/1/5.
 */
public class CacheContext<T> {

    private Map<String, T> cache = Maps.newConcurrentMap();

    public T get(String key){
        return  cache.get(key);
    }

    public void addOrUpdateCache(String key,T value) {
        cache.put(key, value);
    }

    // 根据 key 来删除缓存中的一条记录
    public void evictCache(String key) {
        if(cache.containsKey(key)) {
            cache.remove(key);
        }
    }

    // 清空缓存中的所有记录
    public void evictCache() {
        cache.clear();
    }

}

好,现在我们有了实体类和一个缓存管理器,还需要一个提供账号查询的服务类,此服务类使用缓存管理器来支持账号查询缓存,如下:

import com.google.common.base.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wenchao.ren
 *         2015/1/5.
 */
@Service
public class AccountService1 {

    private final Logger logger = LoggerFactory.getLogger(AccountService1.class);

    @Resource
    private CacheContext<Account> accountCacheContext;

    public Account getAccountByName(String accountName) {
        Account result = accountCacheContext.get(accountName);
        if (result != null) {
            logger.info("get from cache... {}", accountName);
            return result;
        }

        Optional<Account> accountOptional = getFromDB(accountName);
        if (!accountOptional.isPresent()) {
            throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
        }

        Account account = accountOptional.get();
        accountCacheContext.addOrUpdateCache(accountName, account);
        return account;
    }

    public void reload() {
        accountCacheContext.evictCache();
    }

    private Optional<Account> getFromDB(String accountName) {
        logger.info("real querying db... {}", accountName);
        //Todo query data from database
        return Optional.fromNullable(new Account(accountName));
    }

}

现在我们开始写一个测试类,用于测试刚才的缓存是否有效

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class AccountService1Test {

    private AccountService1 accountService1;

    private final Logger logger = LoggerFactory.getLogger(AccountService1Test.class);

    @Before
    public void setUp() throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext1.xml");
        accountService1 = context.getBean("accountService1", AccountService1.class);
    }

    @Test
    public void testInject(){
        assertNotNull(accountService1);
    }

    @Test
    public void testGetAccountByName() throws Exception {
        accountService1.getAccountByName("accountName");
        accountService1.getAccountByName("accountName");

        accountService1.reload();
        logger.info("after reload ....");

        accountService1.getAccountByName("accountName");
        accountService1.getAccountByName("accountName");
    }
}

按照分析,执行结果应该是:首先从数据库查询,然后直接返回缓存中的结果,重置缓存后,应该先从数据库查询,然后返回缓存中的结果. 查看程序运行的日志如下:

00:53:17.166 [main] INFO  c.r.s.cache.example1.AccountService - real querying db... accountName
00:53:17.168 [main] INFO  c.r.s.cache.example1.AccountService - get from cache... accountName
00:53:17.168 [main] INFO  c.r.s.c.example1.AccountServiceTest - after reload ....
00:53:17.168 [main] INFO  c.r.s.cache.example1.AccountService - real querying db... accountName
00:53:17.169 [main] INFO  c.r.s.cache.example1.AccountService - get from cache... accountName

可以看出我们的缓存起效了,但是这种自定义的缓存方案有如下劣势:

  • 缓存代码和业务代码耦合度太高,如上面的例子,AccountService 中的 getAccountByName()方法中有了太多缓存的逻辑,不便于维护和变更
  • 不灵活,这种缓存方案不支持按照某种条件的缓存,比如只有某种类型的账号才需要缓存,这种需求会导致代码的变更
  • 缓存的存储这块写的比较死,不能灵活的切换为使用第三方的缓存模块

如果你的代码中有上述代码的影子,那么你可以考虑按照下面的介绍来优化一下你的代码结构了,也可以说是简化,你会发现,你的代码会变得优雅的多!

Spring cache是如何做的呢

我们对AccountService1 进行修改,创建AccountService2:

import com.google.common.base.Optional;
import com.rollenholt.spring.cache.example1.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author wenchao.ren
 *         2015/1/5.
 */
@Service
public class AccountService2 {

    private final Logger logger = LoggerFactory.getLogger(AccountService2.class);

    // 使用了一个缓存名叫 accountCache
    @Cacheable(value="accountCache")
    public Account getAccountByName(String accountName) {

        // 方法内部实现不考虑缓存逻辑,直接实现业务
        logger.info("real querying account... {}", accountName);
        Optional<Account> accountOptional = getFromDB(accountName);
        if (!accountOptional.isPresent()) {
            throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
        }

        return accountOptional.get();
    }

    private Optional<Account> getFromDB(String accountName) {
        logger.info("real querying db... {}", accountName);
        //Todo query data from database
        return Optional.fromNullable(new Account(accountName));
    }

}

我们注意到在上面的代码中有一行:

     @Cacheable(value="accountCache")
     

这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。这里的缓存中的 key 就是参数 accountName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。我们还需要一个 spring 的配置文件来支持基于注释的缓存

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

    <context:component-scan base-package="com.rollenholt.spring.cache"/>

    <context:annotation-config/>

    <cache:annotation-driven/>

    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
                    <property name="name" value="default"/>
                </bean>
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
                    <property name="name" value="accountCache"/>
                </bean>
            </set>
        </property>
    </bean>

</beans>

注意这个 spring 配置文件有一个关键的支持缓存的配置项:

<cache:annotation-driven />

这个配置项缺省使用了一个名字叫 cacheManager 的缓存管理器,这个缓存管理器有一个 spring 的缺省实现,即 org.springframework.cache.support.SimpleCacheManager,这个缓存管理器实现了我们刚刚自定义的缓存管理器的逻辑,它需要配置一个属性 caches,即此缓存管理器管理的缓存集合,除了缺省的名字叫 default 的缓存,我们还自定义了一个名字叫 accountCache 的缓存,使用了缺省的内存存储方案 ConcurrentMapCacheFactoryBean,它是基于 java.util.concurrent.ConcurrentHashMap 的一个内存缓存实现方案。

然后我们编写测试程序:

 import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class AccountService2Test {

    private AccountService2 accountService2;

    private final Logger logger = LoggerFactory.getLogger(AccountService2Test.class);

    @Before
    public void setUp() throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
        accountService2 = context.getBean("accountService2", AccountService2.class);
    }

    @Test
    public void testInject(){
        assertNotNull(accountService2);
    }

    @Test
    public void testGetAccountByName() throws Exception {
        logger.info("first query...");
        accountService2.getAccountByName("accountName");

        logger.info("second query...");
        accountService2.getAccountByName("accountName");
    }
}

上面的测试代码主要进行了两次查询,第一次应该会查询数据库,第二次应该返回缓存,不再查数据库,我们执行一下,看看结果

01:10:32.435 [main] INFO  c.r.s.c.example2.AccountService2Test - first query...
01:10:32.456 [main] INFO  c.r.s.cache.example2.AccountService2 - real querying account... accountName
01:10:32.457 [main] INFO  c.r.s.cache.example2.AccountService2 - real querying db... accountName
01:10:32.458 [main] INFO  c.r.s.c.example2.AccountService2Test - second query...

可以看出我们设置的基于注释的缓存起作用了,而在 AccountService.java 的代码中,我们没有看到任何的缓存逻辑代码,只有一行注释:@Cacheable(value="accountCache"),就实现了基本的缓存方案,是不是很强大?

如何清空缓存

好,到目前为止,我们的 spring cache 缓存程序已经运行成功了,但是还不完美,因为还缺少一个重要的缓存管理逻辑:清空缓存.

当账号数据发生变更,那么必须要清空某个缓存,另外还需要定期的清空所有缓存,以保证缓存数据的可靠性。

为了加入清空缓存的逻辑,我们只要对 AccountService2.java 进行修改,从业务逻辑的角度上看,它有两个需要清空缓存的地方

  • 当外部调用更新了账号,则我们需要更新此账号对应的缓存
  • 当外部调用说明重新加载,则我们需要清空所有缓存

我们在AccountService2的基础上进行修改,修改为AccountService3,代码如下:

import com.google.common.base.Optional;
import com.rollenholt.spring.cache.example1.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author wenchao.ren
 *         2015/1/5.
 */
@Service
public class AccountService3 {

    private final Logger logger = LoggerFactory.getLogger(AccountService3.class);

    // 使用了一个缓存名叫 accountCache
    @Cacheable(value="accountCache")
    public Account getAccountByName(String accountName) {

        // 方法内部实现不考虑缓存逻辑,直接实现业务
        logger.info("real querying account... {}", accountName);
        Optional<Account> accountOptional = getFromDB(accountName);
        if (!accountOptional.isPresent()) {
            throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
        }

        return accountOptional.get();
    }

    @CacheEvict(value="accountCache",key="#account.getName()")
    public void updateAccount(Account account) {
        updateDB(account);
    }

    @CacheEvict(value="accountCache",allEntries=true)
    public void reload() {
    }

    private void updateDB(Account account) {
        logger.info("real update db...{}", account.getName());
    }

    private Optional<Account> getFromDB(String accountName) {
        logger.info("real querying db... {}", accountName);
        //Todo query data from database
        return Optional.fromNullable(new Account(accountName));
    }
}

我们的测试代码如下:

import com.rollenholt.spring.cache.example1.Account;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AccountService3Test {


    private AccountService3 accountService3;

    private final Logger logger = LoggerFactory.getLogger(AccountService3Test.class);

    @Before
    public void setUp() throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
        accountService3 = context.getBean("accountService3", AccountService3.class);
    }

    @Test
    public void testGetAccountByName() throws Exception {

        logger.info("first query.....");
        accountService3.getAccountByName("accountName");

        logger.info("second query....");
        accountService3.getAccountByName("accountName");

    }

    @Test
    public void testUpdateAccount() throws Exception {
        Account account1 = accountService3.getAccountByName("accountName1");
        logger.info(account1.toString());
        Account account2 = accountService3.getAccountByName("accountName2");
        logger.info(account2.toString());

        account2.setId(121212);
        accountService3.updateAccount(account2);

        // account1会走缓存
        account1 = accountService3.getAccountByName("accountName1");
        logger.info(account1.toString());
        // account2会查询db
        account2 = accountService3.getAccountByName("accountName2");
        logger.info(account2.toString());

    }

    @Test
    public void testReload() throws Exception {
        accountService3.reload();
        // 这2行查询数据库
        accountService3.getAccountByName("somebody1");
        accountService3.getAccountByName("somebody2");

        // 这两行走缓存
        accountService3.getAccountByName("somebody1");
        accountService3.getAccountByName("somebody2");
    }
}

在这个测试代码中我们重点关注testUpdateAccount()方法,在测试代码中我们已经注释了在update完account2以后,再次查询的时候,account1会走缓存,而account2不会走缓存,而去查询db,观察程序运行日志,运行日志为:

01:37:34.549 [main] INFO  c.r.s.cache.example3.AccountService3 - real querying account... accountName1
01:37:34.551 [main] INFO  c.r.s.cache.example3.AccountService3 - real querying db... accountName1
01:37:34.552 [main] INFO  c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName1'}
01:37:34.553 [main] INFO  c.r.s.cache.example3.AccountService3 - real querying account... accountName2
01:37:34.553 [main] INFO  c.r.s.cache.example3.AccountService3 - real querying db... accountName2
01:37:34.555 [main] INFO  c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName2'}
01:37:34.555 [main] INFO  c.r.s.cache.example3.AccountService3 - real update db...accountName2
01:37:34.595 [main] INFO  c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName1'}
01:37:34.596 [main] INFO  c.r.s.cache.example3.AccountService3 - real querying account... accountName2
01:37:34.596 [main] INFO  c.r.s.cache.example3.AccountService3 - real querying db... accountName2
01:37:34.596 [main] INFO  c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName2'}

我们会发现实际运行情况和我们预估的结果是一致的。

如何按照条件操作缓存

前面介绍的缓存方法,没有任何条件,即所有对 accountService 对象的 getAccountByName 方法的调用都会起动缓存效果,不管参数是什么值。

如果有一个需求,就是只有账号名称的长度小于等于 4 的情况下,才做缓存,大于 4 的不使用缓存

虽然这个需求比较坑爹,但是抛开需求的合理性,我们怎么实现这个功能呢?

通过查看CacheEvict注解的定义,我们会发现:

/**
 * Annotation indicating that a method (or all methods on a class) trigger(s)
 * a cache invalidate operation.
 *
 * @author Costin Leau
 * @author Stephane Nicoll
 * @since 3.1
 * @see CacheConfig
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CacheEvict {

    /**
     * Qualifier value for the specified cached operation.
     * <p>May be used to determine the target cache (or caches), matching the qualifier
     * value (or the bean name(s)) of (a) specific bean definition.
     */
    String[] value() default {};

    /**
     * Spring Expression Language (SpEL) attribute for computing the key dynamically.
     * <p>Default is "", meaning all method parameters are considered as a key, unless
     * a custom {@link #keyGenerator()} has been set.
     */
    String key() default "";

    /**
     * The bean name of the custom {@link org.springframework.cache.interceptor.KeyGenerator} to use.
     * <p>Mutually exclusive with the {@link #key()} attribute.
     */
    String keyGenerator() default "";

    /**
     * The bean name of the custom {@link org.springframework.cache.CacheManager} to use to
     * create a default {@link org.springframework.cache.interceptor.CacheResolver} if none
     * is set already.
     * <p>Mutually exclusive with the {@link #cacheResolver()}  attribute.
     * @see org.springframework.cache.interceptor.SimpleCacheResolver
     */
    String cacheManager() default "";

    /**
     * The bean name of the custom {@link org.springframework.cache.interceptor.CacheResolver} to use.
     */
    String cacheResolver() default "";

    /**
     * Spring Expression Language (SpEL) attribute used for conditioning the method caching.
     * <p>Default is "", meaning the method is always cached.
     */
    String condition() default "";

    /**
     * Whether or not all the entries inside the cache(s) are removed or not. By
     * default, only the value under the associated key is removed.
     * <p>Note that setting this parameter to {@code true} and specifying a {@link #key()}
     * is not allowed.
     */
    boolean allEntries() default false;

    /**
     * Whether the eviction should occur after the method is successfully invoked (default)
     * or before. The latter causes the eviction to occur irrespective of the method outcome (whether
     * it threw an exception or not) while the former does not.
     */
    boolean beforeInvocation() default false;
}

定义中有一个condition描述:

Spring Expression Language (SpEL) attribute used for conditioning the method caching.Default is "", meaning the method is always cached.

我们可以利用这个方法来完成这个功能,下面只给出示例代码:

@Cacheable(value="accountCache",condition="#accountName.length() <= 4")// 缓存名叫 accountCache 
public Account getAccountByName(String accountName) {
    // 方法内部实现不考虑缓存逻辑,直接实现业务
    return getFromDB(accountName);
}

注意其中的 condition=”#accountName.length() <=4”,这里使用了 SpEL 表达式访问了参数 accountName 对象的 length() 方法,条件表达式返回一个布尔值,true/false,当条件为 true,则进行缓存操作,否则直接调用方法执行的返回结果。

如果有多个参数,如何进行 key 的组合

我们看看CacheEvict注解的key()方法的描述:

Spring Expression Language (SpEL) attribute for computing the key dynamically. Default is "", meaning all method parameters are considered as a key, unless a custom {@link #keyGenerator()} has been set.

假设我们希望根据对象相关属性的组合来进行缓存,比如有这么一个场景:

要求根据账号名、密码和是否发送日志查询账号信息

很明显,这里我们需要根据账号名、密码对账号对象进行缓存,而第三个参数“是否发送日志”对缓存没有任何影响。所以,我们可以利用 SpEL 表达式对缓存 key 进行设计

我们为Account类增加一个password 属性, 然后修改AccountService代码:

 @Cacheable(value="accountCache",key="#accountName.concat(#password)") 
 public Account getAccount(String accountName,String password,boolean sendLog) { 
   // 方法内部实现不考虑缓存逻辑,直接实现业务
   return getFromDB(accountName,password); 
 }
 

注意上面的 key 属性,其中引用了方法的两个参数 accountName 和 password,而 sendLog 属性没有考虑,因为其对缓存没有影响。

accountService.getAccount("accountName", "123456", true);// 查询数据库
accountService.getAccount("accountName", "123456", true);// 走缓存
accountService.getAccount("accountName", "123456", false);// 走缓存
accountService.getAccount("accountName", "654321", true);// 查询数据库
accountService.getAccount("accountName", "654321", true);// 走缓存

如何做到:既要保证方法被调用,又希望结果被缓存

根据前面的例子,我们知道,如果使用了 @Cacheable 注释,则当重复使用相同参数调用方法的时候,方法本身不会被调用执行,即方法本身被略过了,取而代之的是方法的结果直接从缓存中找到并返回了。

现实中并不总是如此,有些情况下我们希望方法一定会被调用,因为其除了返回一个结果,还做了其他事情,例如记录日志,调用接口等,这个时候,我们可以用 @CachePut 注释,这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中。

@Cacheable(value="accountCache")
 public Account getAccountByName(String accountName) { 
   // 方法内部实现不考虑缓存逻辑,直接实现业务
   return getFromDB(accountName); 
 } 

 // 更新 accountCache 缓存
 @CachePut(value="accountCache",key="#account.getName()")
 public Account updateAccount(Account account) { 
   return updateDB(account); 
 } 
 private Account updateDB(Account account) { 
   logger.info("real updating db..."+account.getName()); 
   return account; 
 }

我们的测试代码如下

Account account = accountService.getAccountByName("someone"); 
account.setPassword("123"); 
accountService.updateAccount(account); 
account.setPassword("321"); 
accountService.updateAccount(account); 
account = accountService.getAccountByName("someone"); 
logger.info(account.getPassword()); 

如上面的代码所示,我们首先用 getAccountByName 方法查询一个人 someone 的账号,这个时候会查询数据库一次,但是也记录到缓存中了。然后我们修改了密码,调用了 updateAccount 方法,这个时候会执行数据库的更新操作且记录到缓存,我们再次修改密码并调用 updateAccount 方法,然后通过 getAccountByName 方法查询,这个时候,由于缓存中已经有数据,所以不会查询数据库,而是直接返回最新的数据,所以打印的密码应该是“321”

@Cacheable、@CachePut、@CacheEvict 注释介绍

  • @Cacheable 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
  • @CachePut 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
    -@CachEvict 主要针对方法配置,能够根据一定的条件对缓存进行清空

基本原理

一句话介绍就是Spring AOP的动态代理技术。 如果读者对Spring AOP不熟悉的话,可以去看看官方文档

扩展性

直到现在,我们已经学会了如何使用开箱即用的 spring cache,这基本能够满足一般应用对缓存的需求。

但现实总是很复杂,当你的用户量上去或者性能跟不上,总需要进行扩展,这个时候你或许对其提供的内存缓存不满意了,因为其不支持高可用性,也不具备持久化数据能力,这个时候,你就需要自定义你的缓存方案了。

还好,spring 也想到了这一点。我们先不考虑如何持久化缓存,毕竟这种第三方的实现方案很多。

我们要考虑的是,怎么利用 spring 提供的扩展点实现我们自己的缓存,且在不改原来已有代码的情况下进行扩展。

���先,我们需要提供一个 CacheManager 接口的实现,这个接口告诉 spring 有哪些 cache 实例,spring 会根据 cache 的名字查找 cache 的实例。另外还需要自己实现 Cache 接口,Cache 接口负责实际的缓存逻辑,例如增加键值对、存储、查询和清空等。

利用 Cache 接口,我们可以对接任何第三方的缓存系统,例如 EHCache、OSCache,甚至一些内存数据库例如 memcache 或者 redis 等。下面我举一个简单的例子说明如何做。

import java.util.Collection; 

 import org.springframework.cache.support.AbstractCacheManager; 

 public class MyCacheManager extends AbstractCacheManager { 
   private Collection<? extends MyCache> caches; 

   /** 
   * Specify the collection of Cache instances to use for this CacheManager. 
   */ 
   public void setCaches(Collection<? extends MyCache> caches) { 
     this.caches = caches; 
   } 

   @Override 
   protected Collection<? extends MyCache> loadCaches() { 
     return this.caches; 
   } 

 }

上面的自定义的 CacheManager 实际继承了 spring 内置的 AbstractCacheManager,实际上仅仅管理 MyCache 类的实例。

下面是MyCache的定义:

import java.util.HashMap; 
 import java.util.Map; 

 import org.springframework.cache.Cache; 
 import org.springframework.cache.support.SimpleValueWrapper; 

 public class MyCache implements Cache { 
   private String name; 
   private Map<String,Account> store = new HashMap<String,Account>();; 

   public MyCache() { 
   } 

   public MyCache(String name) { 
     this.name = name; 
   } 

   @Override 
   public String getName() { 
     return name; 
   } 

   public void setName(String name) { 
     this.name = name; 
   } 

   @Override 
   public Object getNativeCache() { 
     return store; 
   } 

   @Override 
   public ValueWrapper get(Object key) { 
     ValueWrapper result = null; 
     Account thevalue = store.get(key); 
     if(thevalue!=null) { 
       thevalue.setPassword("from mycache:"+name); 
       result = new SimpleValueWrapper(thevalue); 
     } 
     return result; 
   } 

   @Override 
   public void put(Object key, Object value) { 
     Account thevalue = (Account)value; 
     store.put((String)key, thevalue); 
   } 

   @Override 
   public void evict(Object key) { 
   } 

   @Override 
   public void clear() { 
   } 
 }
 

上面的自定义缓存只实现了很简单的逻辑,但这是我们自己做的,也很令人激动是不是,主要看 get 和 put 方法,其中的 get 方法留了一个后门,即所有的从缓存查询返回的对象都将其 password 字段设置为一个特殊的值,这样我们等下就能演示“我们的缓存确实在起作用!”了。

这还不够,spring 还不知道我们写了这些东西,需要通过 spring*.xml 配置文件告诉它

 <cache:annotation-driven /> 

 <bean id="cacheManager" class="com.rollenholt.spring.cache.MyCacheManager">
     <property name="caches"> 
       <set> 
         <bean 
           class="com.rollenholt.spring.cache.MyCache"
           p:name="accountCache" /> 
       </set> 
     </property> 
   </bean> 
   

接下来我们来编写测试代码:

Account account = accountService.getAccountByName("someone"); 
logger.info("passwd={}", account.getPassword()); 
account = accountService.getAccountByName("someone"); 
logger.info("passwd={}", account.getPassword()); 

上面的测试代码主要是先调用 getAccountByName 进行一次查询,这会调用数据库查询,然后缓存到 mycache 中,然后我打印密码,应该是空的;下面我再次查询 someone 的账号,这个时候会从 mycache 中返回缓存的实例,记得上面的后门么?我们修改了密码,所以这个时候打印的密码应该是一个特殊的值

注意和限制

基于 proxy 的 spring aop 带来的内部调用问题

上面介绍过 spring cache 的原理,即它是基于动态生成的 proxy 代理机制来对方法的调用进行切面,这里关键点是对象的引用问题.

如果对象的方法是内部调用(即 this 引用)而不是外部引用,则会导致 proxy 失效,那么我们的切面就失效,也就是说上面定义的各种注释包括 @Cacheable、@CachePut 和 @CacheEvict 都会失效,我们来演示一下。

public Account getAccountByName2(String accountName) { 
   return this.getAccountByName(accountName); 
 } 

 @Cacheable(value="accountCache")// 使用了一个缓存名叫 accountCache 
 public Account getAccountByName(String accountName) { 
   // 方法内部实现不考虑缓存逻辑,直接实现业务
   return getFromDB(accountName); 
 }
 

上面我们定义了一个新的方法 getAccountByName2,其自身调用了 getAccountByName 方法,这个时候,发生的是内部调用(this),所以没有走 proxy,导致 spring cache 失效

要避免这个问题,就是要避免对缓存方法的内部调用,或者避免使用基于 proxy 的 AOP 模式,可以使用基于 aspectJ 的 AOP 模式来解决这个问题。

@CacheEvict 的可靠性问题

我们看到,@CacheEvict 注释有一个属性 beforeInvocation,缺省为 false,即缺省情况下,都是在实际的方法执行完成后,才对缓存进行清空操作。期间如果执行方法出现异常,则会导致缓存清空不被执行。我们演示一下

// 清空 accountCache 缓存
 @CacheEvict(value="accountCache",allEntries=true)
 public void reload() { 
   throw new RuntimeException(); 
 }
 

我们的测试代码如下:

   accountService.getAccountByName("someone"); 
   accountService.getAccountByName("someone"); 
   try { 
     accountService.reload(); 
   } catch (Exception e) { 
    //...
   } 
   accountService.getAccountByName("someone"); 
   

注意上面的代码,我们在 reload 的时候抛出了运行期异常,这会导致清空缓存失败。上面的测试代码先查询了两次,然后 reload,然后再查询一次,结果应该是只有第一次查询走了数据库,其他两次查询都从缓存,第三次也走缓存因为 reload 失败了。

那么我们如何避免这个问题呢?我们可以用 @CacheEvict 注释提供的 beforeInvocation 属性,将其设置为 true,这样,在方法执行前我们的缓存就被清空了。可以确保缓存被清空。

非 public 方法问题

和内部调用问题类似,非 public 方法如果想实现基于注释的缓存,必须采用基于 AspectJ 的 AOP 机制

Dummy CacheManager 的配置和作用

有的时候,我们在代码迁移、调试或者部署的时候,恰好没有 cache 容器,比如 memcache 还不具备条件,h2db 还没有装好等,如果这个时候你想调试代码,岂不是要疯掉?这里有一个办法,在不具备缓存条件的时候,在不改代码的情况下,禁用缓存。

方法就是修改 spring*.xml 配置文件,设置一个找不到缓存就不做任何操作的标志位,如下

   <cache:annotation-driven /> 

   <bean id="simpleCacheManager" class="org.springframework.cache.support.SimpleCacheManager"> 
     <property name="caches"> 
       <set> 
         <bean 
           class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
           p:name="default" /> 
       </set> 
     </property> 
   </bean> 

   <bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
     <property name="cacheManagers"> 
       <list> 
         <ref bean="simpleCacheManager" /> 
       </list> 
     </property> 
     <property name="fallbackToNoOpCache" value="true" /> 
   </bean> 

注意以前的 cacheManager 变为了 simpleCacheManager,且没有配置 accountCache 实例,后面的 cacheManager 的实例是一个 CompositeCacheManager,他利用了前面的 simpleCacheManager 进行查询,如果查询不到,则根据标志位 fallbackToNoOpCache 来判断是否不做任何缓存操作。

使用 guava cache

<bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
    <property name="cacheSpecification" value="concurrencyLevel=4,expireAfterAccess=100s,expireAfterWrite=100s" />
    <property name="cacheNames">
        <list>
            <value>dictTableCache</value>
        </list>
    </property>
</bean>
Spring Cache的详细使用(Redis) Spring 3.1起,提供了基于注解的对Cache的支持。Spring提供了各种xxxCache的实现(如redis缓存)。使用Spring Cache的好处:基于注解,代码清爽简洁可以对缓存进行回滚基于注解也可以实现复杂的逻辑Spring Cache不是具体的缓存技术,而是基于具体的缓存产品(如Guava、EhCache、Redis等)的共性进行了一层封装,但是可以通过简单的配置切换底层使用的缓存。具体的底层缓存技术究竟采用了Guava、EhCache还是Redis,只需要简单的配置就可以实现方便的切换 阅读详情

相关推荐

@CacheInvalidate(name = “xxx“, key = “#results.![a+b]“,multi = true)是什么意思

JetCache 是一款基于注解的缓存框架,提供了丰富的缓存功能和灵活的配置选项,可用于增强应用程序的性能和可扩展性。使用 @CacheInvalidate 注解,可以方便地在方法执行后无效化指定的缓存数据,确保下次访问时能够获取最新的数据。它的作用是在指定的缓存中,根据给定的条件,使缓存中的数据无效化(即删除或失效)。属性的组合作为缓存的键(key),将缓存中匹配的数据进行无效化。属性发生变化时,通过该代码可以立即使缓存中与这些变化相关的数据失效,以确保下次访问时能够重新从数据源获取最新的数据。

1691

SpringCachemanager使用Cache(redis作为缓存中间件)

cacheManager

奔跑的菜鸡 3425

CacheManager.java 管理缓存

package com.cnfilm.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; /** * 文件名:CacheManager.java 管理缓存 * 版本信息:V1.0 * 日期:2013-06-18 * Copyright BDVCD Corporation 2013 * 版权所有 http://www.bdvcd.com * */ @SuppressWarnings("all") public class CacheManager { private static HashMap cacheMap = new HashMap(); /** * 单实例构造方法 */ private CacheManager() { super(); } /** * 得到缓存。同步静态方法 * * @param key * @return */ public synchronized static Object getCache(String key) { return cacheMap.get(key); } /** * 判断是否存在一个缓存 * * @param key * @return */ public synchronized static boolean hasCache(String key) { return cacheMap.containsKey(key); } /** * 清除所有缓存 */ public synchronized static void clearAll() { cacheMap.clear(); } /** * 清除指定的缓存 * * @param key */ public synchronized static void clearOnly(String key) { cacheMap.remove(key); } /** * 载入缓存 * * @param key * @param obj */ public synchronized static void putCache(String key, Object obj) { cacheMap.put(key, obj); } }

分布式-多级缓存

1. 介绍 1.1 简介 JetCache是一个基于Java的缓存系统封装,提供统一的API和注解来简化缓存的使用。 JetCache提供了比SpringCache更加强大的注解,可以原生的支持TTL、两级缓存、分布式自动刷新,还提供了Cache接口用于手工缓存操作。 1.2 特性 通过统一的API访问Cache系统 通过注解实现声明式的方法缓存,支持TTL和两级缓存 通过注解创建并配置Cache实例 针对所有Cache实例和方法缓存的自动统计 Key的生成策略和Value的序列化策略是可以

皮皮皮的代码 1878

Win10环境借助DockerDesktop部署Open web UI集成DeepSeek

Win10环境借助DockerDesktop部署Open web UI集成DeepSeek,并借助DuckDuckGo实现联网查询

虎鲸不是鱼 1700

【02】【VisionMaster V4.0.0 】安装教程—— 授权文件更新报错:应用程序与本地LM通讯出错(怀疑电脑加密 和 上网受限 造成的 )

本文详细介绍了海康VisionMaster 4.0试用版的安装流程及常见问题解决方案。主要内容包括:1)从官网下载基础安装包、试用补丁和授权文件;2)按顺序安装主程序、补丁和授权文件;3)针对授权失败问题提供两种解决方案(更换未加密电脑或使用加密狗);4)说明试用版的功能限制(30天试用期、2个流程限制等)。文章特别指出电脑加密可能导致授权失败,并提供了安装报错时的处理建议,为初次使用者提供了完整的安装指导。

程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。 7170

Spring Cache详解

从3.1开始,Spring引入了对Cache的支持。其使用方法和原理都类似于Spring对事务管理的支持。Spring Cache是作用在方法上的,其核心思想是这样的:当调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。所以在使用Spring Cache的时候要保证缓存的方法对于相同的方法参数要有相同的返回结果。

JAVA_KX的博客 2316

基于FPGA的TDC延迟链优化与码密度校准方法(1)——原理与实现

本文深入探讨了基于FPGA的时间数字转换器(TDC)延迟链非均匀性问题及其码密度校准方法。通过分析工艺偏差、温度电压影响等根源,详细介绍了码密度测试原理、逐位校准技术及气泡消除算法,并分享了自适应校准策略与多场景应用实践,有效提升TDC测量精度至皮秒级。

kiwi8的博客 488

Spring Cache使用

Spring Cache 是 Spring Framework 提供的一种缓存抽象,旨在简化缓存的使用和集成。它使得开发者可以通过注解方式轻松地对方法的返回结果进行缓存,从而提升应用程序的性能,尤其是在访问频繁但计算开销较大的操作时。Spring Cache 提供了一个一致的缓存抽象,支持多种缓存技术,比如:EhcacheRedisGuavaCaffeine它提供了注解式的缓存配置,并且能够与现有的缓存解决方案无缝集成。

2303_80195175的博客 1668

Isaac Sim 6 利用Replicator实现高效语义分割与实例分割(实践指南5.10)

本文详细介绍了如何利用Isaac Sim 6的Replicator工具高效生成语义分割和实例分割数据集。通过虚拟环境自动标注,效率提升20倍以上,特别适用于农业机器人等计算机视觉项目。文章包含环境配置、场景构建、批量标注技巧及实例分割处理等实战指南,帮助开发者快速掌握合成数据生成技术。

weixin_42526415的博客 266

六维力传感器选型指南:电阻式vs电容式,哪个更适合你的工业场景?

本文深入解析六维力传感器在工业自动化中的选型要点,重点对比电阻式与电容式传感器的核心原理、环境适应性及成本结构。针对不同工业场景(如高精度装配、重载机器人等),提供专业选型建议,帮助工程师优化系统性能与经济效益。

weixin_42525005的博客 395

Spring Cache的基本使用

Spring Cache的基本使用:环境搭建、@Cacheable、@CachePut、@CacheEvict等注解的使用......

学习记录和总结 4948

别急着让AI画板!聊聊Cadence Allegro X AI和OrCAD X在实际PCB项目中的真实体验

本文分享了Cadence Allegro X AI与OrCAD X在PCB设计中的实际应用体验,探讨了AI辅助Layout的效率提升与潜在陷阱。通过高速ADC采集板案例,详细对比了AI与传统方法在电源平面分割、低速信号布线等任务中的表现,并总结了人机协作的最佳实践,为工程师提供实用参考。

weixin_30836759的博客 2209

spring cache

1.想用redistemplate作为缓存,被领导制止了,指定用spring cache 2.自我理解:spring cache也是一个缓存,方便存储对象,但是缓存底层可以选择redis 3.spring cache+redis的好处 解决缓存不同步的情况 解决springcache占用内存的情况 集群环境下,每台服务器的spring cache是不同步的,这样会出问题的, spring cache只适合单机环境 redis是设置单独的缓存服务器,所有集群服务器统一访问redis,不会出现...

qq_35653822的博客 1105

Allegro基本规则设置指导书之Spacing Region

当网络需要在Region中需要按照自身的规则匹配时,可以创建Region Class来匹配。Region也支持Class to Class规则,点击ok即可。Allegro基本规则设置指导书之Spacing Region。下面介绍基本规则设置指导书之Spacing Region。给创建好的Region 匹配一个规则。空白的地方创建一个Region。

weixin_54787054的博客 564

5实践报告撰写

一 项目流程 明确标准 确定分析目标 寻找分析数据 清洗数据 描述性分析 诊断性分析 提出建议 撰写报告 二 确定分析目标 什么是你感兴趣的? 什么是你熟悉的? 什么是你擅长的? 1 电商零售行业 商品销量分析 价格分析 评价分析 ...... 2 自媒体行业 广告投放力度分析 广告投放回报分析 不同类型的产品分析 ...... 3 金融行业 股票价格分析 信贷业务违约分析 客户画像分析 ...... ...

waywardG的博客 2832

Spring Cache和redis结合使用

Spring Cache和redis结合使用

xushuai2333333的博客 2150

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Spring 自带缓存Spring Cache

原理:基于Proxy/AspectJ动态代理技术的AOP思想(面向切面编程) 使用: SpringCache包含两个顶级接口,Cache(缓存)和CacheManager(缓存管理器),顾名思义,用CacheManager去管理一堆Cache。 spring cache实现有基于XML/注解实现AOP; CacheManager负责对缓存的增删改查, CacheManager的缓存的介质可配置, 如:ConcurrentMap/EhCache/Redis等。当没有加入EhCache或者Redis依赖时默认

一名后端程序猿 6003

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Spring Cache的使用及实现原理

Spring Cache 概念从Spring 3.1版本开始,提供了一种透明的方式来为现有的Spring 应用添加cache,使用起来就像@Transaction一样。在...

JAVA上尉 2283

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

使用spring cache和ehcache

一.spring cache Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。所以在使用Spring Cache的时候我们要保证我们缓存的方法对于相同的方法参数要有相同的返回结果。使用Spring Cache需...

王小汪的博客 670

Spring Cache 简介

org.springframework.cache; org.springframework.cache.Cache org.springframework.cache.CacheManager 依赖 <dependency> <groupId>org.springframework.boot</groupId>...

dizan4060的博客 124

Spring Cache的使用

一、简介1. Spring Cache是Spring提供的一个缓存框架,在Spring3.1版本开始支持将缓存添加到现有的spring应用程序中,在4.1开始,缓存已支持JSR-107注释和更多自定义的选项。1. Spring Cache利用了**AOP**,实现了基于注解的缓存功能,并且进行了合理的抽象,业务代码不用关心底层是使用了什么缓存框架,**只需要简单地加一个注解,就能实现缓存功能了,做到了对代码侵入性做小。**

zhzjn的博客 1038

spring boot 整合 spring cache 简单使用

Spring Cache 简单使用

weixin_44669022的博客 567

Spring之Cache——Spring缓存架构解读

Spring之Cache——Spring缓存架构解读 Spring之Cache架构 缓存架构的概述 缓存架构的实现 缓存架构的操作原理 Spring Cache 概述 接下来将对Spring的缓存模块进行解读,主要内容分为:缓存的介绍、缓存的实现、两个部分。由于应用部分在网上的教程比较多,例如采用redis等,这里就不再重复了,只讲解Cache架构。 一.缓存架构的概述 作用与功能 ...

rekingman的博客 2467
上一篇: java中的内部类总结
下一篇: MySQL的语句执行顺序
java_hch
博客等级 码龄14年 14粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值