SpringBoot中Cache的正确使用

上篇文章介绍了各种缓存技术,前端技术等来提高web程序的性能,这篇文章主要介绍SpringBoot中的缓存技术来提高系统性能。在使用SpringBoot缓存技术使用比较简单,但也需要注意一些问题。本节先介绍 Spring Boot 自带的in-memory缓存,然后再介绍 EhCahce 和 Redis 缓存。一般in-memory缓存仅单体应用或者是一个小微系统,不适合用在分布式环境下。通常应用为分布式应用时,则需要集成 EhCache、Redis 等分布式缓存管理器。

为什么使用Spring Cache

没有SpringBoot之前,我们集成缓存,一般都是通过根据缓存技术提供的接口来实现缓存,每种缓存都需要单独实现,需要考虑线程安全,缓存过期,缓存高可用等等,不是一件简单的事。而Spring Cache 对 Cahce 进行了抽象,提供了 @Cacheable、@CachePut、@CacheEvict 等注解。Spring Boot 应用基于 Spring Cache,既提供了基于内存实现的缓存管理器,可以用于单体应用系统,也集成了 EhCache、Redis 等缓存服务器,可以用于大型系统或者分布式系统,因此可以根据自己的项目需求选择合理的缓存方案。关键它可以通过注解配置方式低侵入的给原有Spring应用增加缓存功能,提高数据访问性能。在Spring Boot中对于缓存的支持,提供了一系列的自动化配置,使我们可以非常方便的使用缓存。我们也可以轻易的在不同缓存方案中切换,无需修改任何代码。

Spring cache核心组件

Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry。定义摘抄如下,从图上就能很好的理解它们之间的关系。

CachingProvider: Create, configure, acquire, manage, and control multiple CacheManager

CacheManager: Create, configure, acquire, manage, and control multiple uniquely named Caches that exist within the context of CacheManager.A CacheManager corresponds to only one CachingProvider

Cache:is managed by Cache Manager, which manages the life cycle of Cache. Cache exists in the context of Cache Manager and is a map-like data structure that temporarily stores key-indexed values.A Cache is owned by only one CacheManager

Entry:is a key-value pair stored in a Cache

Expiry: Each entry stored in a Cache has a defined expiration date.Once this time is exceeded, the entries will automatically expire, after which they will not be accessible, updated, and deleted.Cache validity can be set through ExpiryPolicy。

SpringBoot Cache常见注解

@CacheConfig,在类上设置当前缓存的一些公共设置,比如缓存名称;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documentedpublic @interface CacheConfig {
    String[] cacheNames() default {};
    String keyGenerator() default "";
    String cacheManager() default "";
    String cacheResolver() default "";
}

@Cacheable,作用在方法上,触发缓存读取操作。表明该方法的结果是可以缓存的,如果缓存存在,则目标方法不会被调用,直接取出缓存。可以为方法声明多个缓存,如果至少有一个缓存有缓存项,则其缓存项将被返回;

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Cacheable {    @AliasFor("cacheNames")    String[] value() default {};        @AliasFor("value")    String[] cacheNames() default {};    String key() default "";    String keyGenerator() default "";    String cacheManager() default "";    String cacheResolver() default "";    String condition() default "";    String unless() default "";    boolean sync() default false;}

@CacheEvict,作用在方法上,触发缓存失效操作,删除缓存项或者清空缓存;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited@Documentedpublic 
@interface CacheEvict {
    @AliasFor("cacheNames")
    String[] value() default {};
    @AliasFor("value")
    String[] cacheNames() default {};
    String key() default "";
    String keyGenerator() default "";
    String cacheManager() default "";
    String cacheResolver() default "";
    String condition() default "";
    boolean allEntries() default false;
    boolean beforeInvocation() default false;
}

@CachePut,作用在方法上,触发缓存更新操作,添加该注解后总是会执行方法体,并且使用返回的结果更新缓存,同 Cacheable 一样,支持 condition、unless、key 选项,也支持 KeyGenerator;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited@Documentedpublic
 @interface CachePut {
    @AliasFor("cacheNames")
    String[] value() default {};
    @AliasFor("value")
    String[] cacheNames() default {};
    String key() default "";
    String keyGenerator() default "";
    String cacheManager() default "";
    String cacheResolver() default "";
    String condition() default "";
    String unless() default "";
}

@Caching,作用在方法上,可以定义复杂的cache规则。

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited@Documentedpublic 
@interface Caching {
    Cacheable[] cacheable() default {};
    CachePut[] put() default {};
    CacheEvict[] evict() default {};
}

使用SpringBoot Cache

Springs Caching Service是一个抽象,不是具体实现,需要用提供具体的cache provider来实现它,SpringBoot支持以下Cache Provider,改变cache provider,不会对现有代码做任何修改,只需要修改配置。

Ehcache 3(本文会介绍)
Hazelcast
Infinispan
Couchbase
Redis(本文会介绍)
CaffeineSimple cache(本文会介绍)

1)开启缓存功能

定义一个CacheConfig配置类,加上@Configuration,@EnableCaching注解,也可以在启动类上添加 @EnableCaching注解。但建议增加一个configuration类,因为有些配置可以在此类中实现,比如key generator等。

@Configuration
@EnableCaching
public class CacheConfig {
}

2)增加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

3)指定cache type

可以在application.properties里指定cache type,当有多个provider同时存在时,需要指定cache type,格式为

spring.cache.type=simple

这是一个enum类型,支持的值为

CAFFEINE
COUCHBASE
EHCACHE
HAZELCAST
INFINISPAN
JCACHENONE
REDIS
SIMPLE

大部分时候不需要指定cache type,SpringBoot会根据POM中引入的provider和配置来装配正确的缓存,除非引入了多个provider,这时需要指定cache type。这是一个容易犯错误的坑,我在项目中就犯过类似错误,因为之前项目中已经使用了Redis,后来我需要使用缓存,但我没有指定cache type,SpringBoot就会使用Redis作为缓存,但由于需要被缓存的数据没有实现序列化,所以导致没法存入到redis中,缓存功能就不生效,后来调试cache源码才发现这个坑,因此,将cache type设为simple,就可以按照Simple缓存方式工作了,不指定就会按照Redis缓存方式,这时类就需要实现序列化。

Simple cache

Spring Boot 自带了基于 ConcurrentHashMap 的 Simple 缓存管理器,使用非常简单,只需要添加spring-boot-starter-cache依赖项。被缓存的对象不需要实现序列化。

CaculationService.java

@Service
@slf4j
public class CalculationService {
  @Cacheable(value = "multiplyCache", key = "{#factor1, #factor2}")
  public double multiply(int factor1, int factor2) {
    log.info("Multiply {} with {}", factor1, factor2);
    return factor1 * factor2;  
  }  
  @CacheEvict(cacheNames = {"multiplyCache"}, allEntries = true)
  public void evictCache() {
    log.info("Evict all cache entries...");  
  }
}

上述是一个简单的calculation实例,第一次访问时会缓存计算结果,后面当相同的请求时直接从内存缓存中获取。使用的key是由参数#factor1,#factor2组成,也可以在config里自定义key generator。可以在@Cacheable中指定cache name,在@CacheEvict中指定多个cache清空,也可以根据清空指定的key。除了使用这些注解操作缓存外,我们也可以使用CacheManager来操作缓存,比如删除缓存,可以按照下面方式实现,同时我们结合Spring定时器来实现定时删除缓存。

@AutoWired
private CacheManager cacheManager;
public void deleteCache() {
        Cache cache = cacheManager.getCache("multiplyCache");
        if(null != cache){
            cache.clear();
        }
}
@Scheduled(fixedRate = 6000)
public void evictAllcachesAtIntervals() {
    deleteCache();
}

CalculationRestController.java

@RestController
@RequestMapping("/rest/calculate")
public class CalculationRestController {
  private final CalculationService calculationService;
  
  @Autowired  
  public CalculationRestController(CalculationService calculationService) {
    this.calculationService = calculationService;  
  }  
  @GetMapping(path = "/multiply", produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<Double> multiply(@RequestParam int factor1, @RequestParam int factor2) {
    double result = calculationService.multiply(factor1, factor2);
    return ResponseEntity.ok(result);
  }
  @GetMapping(path = "/evict", produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<String> evictCache() {
    calculationService.evictCache();
    return ResponseEntity.ok("Cache successfully evicted!");  
  }
}

EHcache

1)增加依赖

<!--for ehcache provoder-->
    <dependency>
        <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>

Spring boot 2之前支持ehcache 2.x,需要引入包net.sf.ehcache。新版本的Spring boot支持ehcache 3.x,需要引入包org.ehcache package。

2)启动缓存

我们也可以自定义key generator,如下,

@Configuration
@EnableCaching
public class EhcacheConfig {
  @Bean
  public KeyGenerator multiplyKeyGenerator() {
    return (Object target, Method method, Object... params) -> method.getName() + "_" + Arrays.toString(params);
  }
}

StudentService.java

@Service
@CacheConfig(cacheNames = "studentCache")
public class StudentService {
  private static AtomicLong ID_CREATOR = new AtomicLong(0);
  private Map<Long, Student> students;
  public StudentService() {
    students = new ConcurrentHashMap<>();
    students.put(ID_CREATOR.incrementAndGet(), new Student(ID_CREATOR.get(), "John", "Doe", "Computer Science"));
    students.put(ID_CREATOR.incrementAndGet(), new Student(ID_CREATOR.get(), "Maria", "Thomson", "Information Systems"));
    students.put(ID_CREATOR.incrementAndGet(), new Student(ID_CREATOR.get(), "Peter", "Simpson", "Mathematics"));
  }
  @Cacheable(keyGenerator = "multiplyKeyGenerator")
  public Optional<Student> find(Long id) {
    LOG.info("Finding student with id '{}'", id);
    return Optional.ofNullable(students.get(id));
  }
  @CachePut(key = "#result.id")
  public Student create(String firstName, String lastName, String courseOfStudies) {
    LOG.info("Creating student with firstName={}, lastName={} and courseOfStudies={}", firstName, lastName, courseOfStudies);
    long newId = ID_CREATOR.incrementAndGet();
    Student newStudent = new Student(newId, firstName, lastName, courseOfStudies);
    students.put(newId, newStudent);
    return newStudent;
  }
}

Student.java

@RequiredArgsConstructor
@Getter@ToString
public class Student implements Serializable {
  private static final long serialVersionUID = 1L;
  private final long id;
  private final String firstName;
  private final String lastName;
  private final String courseOfStudies;
}

注意,Student一定需要实现Serializable,否则缓存无法工作。

3)配置cache

ehcache.xml

<config        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'        xmlns='http://www.ehcache.org/v3'
        xsi:schemaLocation="http://www.ehcache.org/v3
            http://www.ehcache.org/schema/ehcache-core-3.7.xsd">
    <!-- Persistent cache directory -->
    <persistence directory="spring-boot-ehcache/cache" />
    <!-- Default cache template -->
    <cache-template name="default">
        <expiry>
            <ttl unit="seconds">30</ttl>
        </expiry>
        <listeners>
            <listener>
                <class>com.example.ehcache.config.CacheLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
                <events-to-fire-on>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
            <heap>1000</heap>
            <offheap unit="MB">10</offheap>
            <disk persistent="true" unit="MB">20</disk>
        </resources>
    </cache-template>
    <cache alias="multiplyCache" uses-template="default">
        <key-type>java.lang.String</key-type>
        <value-type>java.lang.Double</value-type>
    </cache>
    <cache alias="studentCache" uses-template="default">
        <key-type>java.lang.String</key-type>
        <value-type>com.example.model.Student</value-type>
    </cache>
</config>

4)实现Cache Event listener

@slf4j
public class CacheLogger implements CacheEventListener<Object, Object> {
  @Override
  public void onEvent(CacheEvent<?, ?> cacheEvent) {
    LOG.info("Key: {} | EventType: {} | Old value: {} | New value: {}",
             cacheEvent.getKey(), cacheEvent.getType(), cacheEvent.getOldValue(), cacheEvent.getNewValue());
  }
}

在实例中,首先定义了一个模板,然后每个缓存可以基于此模板来设置每个缓存的key type和value type。支持Java的基本类型和类。listener可以监控cache的事件。

5)设置properties

spring.cache.jcache.config=classpath:ehcache.xml

Redis cache

Redis cache和EHCache类似,只需要引入redis provider和redis的相应配置即可,缓存类也必须实现序列化。

写在最后

使用SpringBoot的Cache使得可以做到代码无侵入的实现缓存,给程序带来很大的性能提升。对数据变化不频繁,请求频率比较高的应用场景是比较适合使用缓存技术。因此,可以根据数据模型,业务场景来设计合适的缓存策略。在使用缓存过程中,需要注意缓存类都需要实现序列化,除了内存缓存外,否则虽然业务功能正常,但缓存功能失效。另外,也需要注意项目中,是不是有多个cache provider,这时最好指定缓存类型。此外,也需要考虑缓存失效和过期时间设置,保证缓存及时更新,避免一些因为缓存问题而导致的Bug。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容