JAVAWeb - SpringBoot - Spring Cache 相关知识

Spring Cache 相关知识

Spring Cache 是 Spring 框架提供的一个缓存抽象层,用于简化应用程序中的缓存管理。通过使用 Spring Cache,开发者可以在不改变业务逻辑的情况下,为方法调用添加缓存功能。Spring Cache 支持多种缓存实现,如 EhCache、Caffeine、Redis 等,并且提供了统一的注解和编程模型来管理缓存。

1. Spring Cache 的核心概念
1.1 缓存抽象

Spring Cache 提供了一个缓存抽象层,使得开发者可以在不依赖具体缓存实现的情况下,使用缓存功能。这意味着你可以在不同的缓存实现之间切换,而不需要修改业务代码。

1.2 缓存管理器

缓存管理器(CacheManager)是 Spring Cache 的核心接口,用于管理一组缓存。Spring 提供了多种缓存管理器的实现,如 SimpleCacheManagerConcurrentMapCacheManagerEhCacheCacheManagerCaffeineCacheManager 等。

1.3 缓存

缓存(Cache)是存储数据的容器。Spring Cache 中的缓存接口定义了基本的缓存操作,如 putgetevictclear

1.4 缓存注解

Spring Cache 提供了多个注解来简化缓存操作,常用的注解包括:

  • @Cacheable:用于标记一个方法的返回值应该被缓存。
  • @CachePut:用于标记一个方法的返回值应该被更新到缓存中。
  • @CacheEvict:用于标记一个方法应该从缓存中移除数据。
  • @Caching:用于组合多个缓存操作。
  • @CacheConfig:用于在类级别共享缓存配置。
2. 配置 Spring Cache
2.1 启用缓存支持

要启用 Spring Cache 支持,需要在 Spring 配置类上添加 @EnableCaching 注解:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {
   
   
    // 配置缓存管理器
}
2.2 配置缓存管理器

Spring 提供了多种缓存管理器的实现,可以根据需要选择合适的缓存管理器。以下是一些常见的缓存管理器配置示例:

2.2.1 SimpleCacheManager

SimpleCacheManager 是一个简单的缓存管理器,使用 ConcurrentMap 作为缓存存储:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {
   
   

    @Bean
    public CacheManager cacheManager() {
   
   
        return new ConcurrentMapCacheManager("cache1", "cache2");
    }
}
2.2.2 EhCacheCacheManager

EhCacheCacheManager 使用 EhCache 作为缓存实现:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
public class CacheConfig {
   
   

    @Bean
    public CacheManager cacheManager() {
   
   
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
   
   
        EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
        factoryBean.setConfigLocation(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值