在这里主要介绍一下springboot怎么使用默认的spring cache缓存
声明式缓存
Spring 定义 CacheManager 和 Cache 接口用来统一不同的缓存技术。例如 JCache、 EhCache、 Hazelcast、 Guava、 Redis 等。在使用 Spring 集成 Cache 的时候,我们需要注册实现的 CacheManager 的 Bean。
Spring Boot 为我们自动配置了 JcacheCacheConfiguration、 EhCacheCacheConfiguration、HazelcastCacheConfiguration、GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration 等。
当我们不适用其他第三方依赖缓存的时候,sprigboot会自动采用ConcurrenMapCacheManager作为缓存管理器。
首先导入依赖
<!--缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
查询数据是用mybatis查询的所有需要导入mybatis相关的依赖,然后配置数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
接着创建实体类,这步我就省略了
然后创建接口
@Mapper
public interface UserMapper {
@Select({"select * from user where id = #{id}"})
User getUser(@Param("id")int id);
}
再创建service接口(我也省略了,直接写实现类)
实现类内容如下
@Service
public class UserServiceImpl {
@Autowired
UserMapper userMapper;
public User getUser(int id){
sleepTime();
return userMapper.getUser(id);
}
// 每次查询都等待1秒钟
private void sleepTime() {
try {
long time = 1000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
方便测试,设置一个等待时间,每次查询都需要等待一秒再执行查询操作
然后就可以测试,直接启动程序
启动程序,你会发现每隔一秒就在控制台打印一次信息,这时还没有开启缓存,接下来开启缓存了再测试一下。
开启缓存技术
首先在程序启动入口加入 @EnableCaching 注解开启缓存技术
@SpringBootApplication
@EnableCaching
public class SpringcacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcacheApplication.class, args);
}
}
然后再在需要缓存的地方加入 @Cacheable 注解
@Cacheable("user")
public User getUser(int id){
sleepTime();
return userMapper.getUser(id);
}
这里在getUser方法上加了 @Cacheable(“user”) 注解,说明这个方法开启了缓存策略,在需要相同的数据时,不用再去重复查询数据库,直接在缓存中拿就可以了
然后启动程序,查看测试结果
可以看到,在第一和二条数据查询完毕后,没有进行等待控制台直接输出了下面的数据,说明缓存起了作用