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,以保证缓存的唯一性。

相关推荐
鱼跃鹰飞33 分钟前
设计模式系列:工厂模式
java·设计模式·系统架构
a努力。1 小时前
国家电网Java面试被问:混沌工程在分布式系统中的应用
java·开发语言·数据库·git·mysql·面试·职场和发展
Yvonne爱编码1 小时前
Java 四大内部类全解析:从设计本质到实战应用
java·开发语言·python
J2虾虾1 小时前
SpringBoot和mybatis Plus不兼容报错的问题
java·spring boot·mybatis
毕设源码-郭学长2 小时前
【开题答辩全过程】以 基于springboot 的豪华婚车租赁系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
Tao____3 小时前
通用性物联网平台
java·物联网·mqtt·低代码·开源
曹轲恒4 小时前
SpringBoot整合SpringMVC(上)
java·spring boot·spring
JH30734 小时前
Java Spring中@AllArgsConstructor注解引发的依赖注入异常解决
java·开发语言·spring
码农水水5 小时前
米哈游Java面试被问:机器学习模型的在线服务和A/B测试
java·开发语言·数据库·spring boot·后端·机器学习·word
2601_949575865 小时前
Flutter for OpenHarmony二手物品置换App实战 - 表单验证实现
android·java·flutter