第一步: 导入spring-boot-starter-cache模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
第二步: @EnableCaching开启缓存
@SpringBootApplication
@MapperScan("com.winter.mapper")
@EnableCaching //开启缓存
//此处必须加包扫描
public class Start {
public static void main(String[] args) {
SpringApplication.run(Start.class, args);
}
}
第三步:bean序列化
注意UID,否则出现序列化错误
public class User implements Serializable
private static final long serialVersionUID = -1421786817532421671L;
第四步: 使用缓存注解
只要给service类/接口增加注解,spring会自动查询缓存
@EnableCaching
//类通用注解
@CacheConfig(cacheNames = "user")
public interface UserService {
//新增缓存
@CachePut(key="#user.userId")
// 注意这里方法返回值必须是User,否则查询缓存出现类转换异常int->User(之前我的返回值是int)
User addUser(User user);
//不同条件的查询放在不同的缓存里,否则会查询到其他方法的缓存值
//这里没有指定key。key默认为pageNum+pageSize的hash值
@Cacheable(cacheNames = "allUser")
List<User> findAllUser(int pageNum, int pageSize);
//查询缓存
@Cacheable(key="#userId")
User selectByPrimaryKey(int userId);
//删除缓存
@CacheEvict(key="#userId")
int deleteByPrimaryKey(int userId);
}
第五步:检查方法返回值
方法返回值的类型,就是key对应的值的类型。如果多个方法共用一个cache且key相同。但是返回值类型不一致,则会造成类转换异常。
测试结果
新增数据后,查询,可以直接查询到缓存种的值,不用查询数据库。 可以看到第二次查询没有sql语句 预编译
配置文件
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: root
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
thymeleaf:
cache: true
redis:
host: xx.xx.x.xxx
port: 6379
password: redis@123
mybatis:
mapper-locations: classpath:mapping/*.xml #注意:一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.winter.model # 注意:对应实体类的路径
configuration:
#开启下划线到驼峰命名法的自动转换,将数据库字段根据驼峰规则自动注入到对象属性
map-underscore-to-camel-case: true
logging:
level:
#打印SQL信息
com.winter.mapper: debug
debug: true
#观察哪些配置类生效
#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
pom文件
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>