Spring Boot Cache - 本地缓存

/ Java / 没有评论 / 2145浏览

针对一些读写比很高的数据,使用本地缓存可以提高效率,如果使用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);
    }
}

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类似,迁移成本很低

其他

spring.cache.type=caffeine

参考