spring的CacheManager

org.springframework.cache.CacheManager是Spring框架中的一个接口,用于管理应用程序中的缓存。它提供了一种抽象的方式来访问缓存,使得应用程序可以使用不同的缓存实现(如内存、Redis等)而不需要修改代码。

在Spring Boot项目中,可以通过在配置类中添加@EnableCaching注解来启用缓存功能,并使用@Bean注解创建CacheManager实例。例如:

复制代码
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("myCache");
    }
}

上述代码中,我们使用ConcurrentMapCacheManager创建了一个名为"myCache"的缓存实例,并将其注入到Spring容器中。

在使用缓存的地方,可以通过@Cacheable注解来标记需要缓存的方法,并指定缓存名称。例如:

复制代码
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Cacheable("myCache")
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

上述代码中,我们通过@Cacheable注解将getUserById方法标记为需要缓存的方法,并指定缓存名称为"myCache"。当该方法被调用时,如果缓存中已经存在对应的结果,则直接返回缓存中的数据,否则执行方法体并将结果存入缓存中。

需要注意的是,@Cacheable注解默认使用方法的参数作为缓存的key,因此在使用时需要保证参数的唯一性。如果需要使用其他方式生成缓存key,可以使用@Cacheable注解的key属性来指定。例如:

复制代码
@Cacheable(value = "myCache", key = "#user.id")
public User saveUser(User user) {
    return userRepository.save(user);
}

上述代码中,我们使用了用户对象的id属性作为缓存key,以保证缓存的唯一性。

相关推荐
海梨花31 分钟前
又是秒杀又是高并发,你的接口真的扛得住吗?
java·后端·jmeter
小肖爱笑不爱笑33 分钟前
2025/11/19 网络编程
java·运维·服务器·开发语言·计算机网络
i***586743 分钟前
springboot中配置logback-spring.xml
spring boot·spring·logback
郑州光合科技余经理1 小时前
开发指南:海外版外卖跑腿系统源码解析与定制
java·开发语言·mysql·spring cloud·uni-app·php·深度优先
SuperherRo1 小时前
JAVA攻防-反序列化利用&JNDI注入&高版本绕过&依赖Jar包&gadge包链&自动Bypass
java·反序列化·jndi·高版本绕过
智语言1 小时前
SpringBoot实战一:五分钟创建第一个Web应用
java
fanruitian2 小时前
Java 静态代码块
java·开发语言
IUGEI2 小时前
【后端开发笔记】JVM底层原理-垃圾回收篇
java·jvm·笔记·后端
迈巴赫车主2 小时前
蓝桥杯 20541魔法科考试
java·数据结构·算法·蓝桥杯
饭饭大王6662 小时前
Python 模块的概念与导入:从基础语法到高级技巧
java·服务器·python