Spring Boot 如何集成Redis
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 在application.properties 里,配置redis(测试环境未给redis配置密码,生产环境是必须的!)
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
- 在Spring Boot 入口文件加上允许缓存
@SpringBootApplication
@MapperScan(basePackages = "com.imooc.mall.model.dao")
@EnableSwagger2
@EnableCaching //这里加上允许缓存
public class MallApplication {
public static void main(String[] args) {
SpringApplication.run(MallApplication.class, args);
}
}
- 在需要用redis缓存的方法上加上注解
@Override
@Cacheable(value = "listCategoryforCustomer") //要选择springframework提供的
public List<CategoryVO> listCategoryforCustomer(){
ArrayList<CategoryVO> categoryVOList = new ArrayList<>();
recursivelyFindCategories(categoryVOList,0);
return categoryVOList;
}
- 配置redis 创建缓存配置类-模板化配置
/**
* @author zj
* @date 2022/3/3 4:26 下午
* @Desc : 缓存的配置类(这里配置是模板化配置,留好直接用即可)
*/
@Configuration
@EnableCaching
public class CachingConfig {
/**
* 主要做的是返回RedisCacheManager 这个对象,而要生成RedisCacheManager需要两个对象,redisCacheWriter和cacheConfiguration
*
* @param connectionFactory
* @return
*/
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory){
// 1. 第一步 利用传入的connectionFactory 生成redisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter
.lockingRedisCacheWriter(connectionFactory);
// 2. 第二步 配置超时时间
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));
// 3. 第三步 生成redisCacheManager
RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,
cacheConfiguration);
return redisCacheManager;
}
}
小坑坑
org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.io.NotSerializableException: com.imooc.mall.model.vo.CategoryVO
这里会有一个小坑,报错:Cannot serialize .
Coding就是不断爬坑的过程 耐心解决
无法序列化,这里要求我们的实体类实现serialize接口
public class CategoryVO implements Serializable {
- 验证是否配置成功-有一下几种方式:
- 第一种:直接postman访问接口查看接口访问时间
第一次请求为缓存前,请求时间为1773ms
第二次请求是已经缓存成功后,请求时间为11ms 这就是缓存成功了
- 第二种验证redis是否配置成功的方法就是利用断点
在第一次请求这个接口时,未缓存就会进入到这个方法中去,停留在此断点。当缓存成功后再次访问就不会在此断点停留。- 第三种验证redis是否配置成功的方法就是直接去redis中看,缓存的key是否存在
- 第三种验证redis是否配置成功的方法就是直接去redis中看,缓存的key是否存在
- 第一种:直接postman访问接口查看接口访问时间
到这里我们就利用了redis缓存了高频访问的接口