Spring Boot Cache - 本地缓存

针对一些读写比很高的数据,使用本地缓存可以提高效率,如果使用Spring Boot框架的话,使用Cache会特别简单。

启动最简单的缓存

添加依赖

pom.xml

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

注解启动缓存

//启动缓存
@EnableCaching
@SpringBootApplication
public class BootCacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootCacheApplication.class, args);
    }
}

使用

@Slf4j
@Service
public class PersonService {
    @Resource
    private PersonMapper personMapper;
    @Cacheable("person")
    public Person getOne(int id) {
        log.info("load one person");
        return personMapper.selectOne(id);
    }

    @CacheEvict(value = "person", key = "#person.id")
    public void update(Person person) {
        personMapper.updateById(person);
    }
}
  • @Cacheable是最主要的注解,它指定了被注解方法的返回值是可被缓存的
  • @CacheEvict注解是@Cacheable注解的反向操作,它负责从给定的缓存中移除一个值

Spring Boot Cache默认使用ConcurrentHashMap作为缓存的实现,只提供了最基础的功能,实际项目中往往需要更加专业的缓存实现。比如Caffeine,EhCache,Redis等

使用Caffeine作为缓存实现

使用Spring Boot Cache框架,其中一个很大的好处,就是可以很方便的更换缓存实现

添加依赖

pom.xml

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.7.0</version>
</dependency>

Spring Boot会检查class path里的类,发现合适的(比如caffeine)就会生成对应的CacheManager

添加特定配置

application.properties

spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=5s

Spring Boot 2已经不支持Guava作为Cache(用户代码内部还是可以使用,只是Spring框架的Cache不支持),代替Guava是的Caffeine,用法跟Guava类似,迁移成本很低

其他

  • 如果classpath有多个缓存组件,可以通过配置指定使用的缓存组件
spring.cache.type=caffeine

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容