1、dao层做缓存
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在启动类上加 @EnableCaching//开启缓存
3、properties文件中写配置
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=172.31.19.222
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
3、redis配置类
4、redis做缓存dao层
注解的作用
@Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key。
@CachePut,指定key,将更新的结果同步到redis中
@CacheEvict,指定key,删除缓存数据,allEntries=true,方法调用后将立即清除缓存
5、事例
@CacheConfig(cacheNames = "users")
public interface UserMapper {
//根据id查询用户
@Cacheable(key ="#p0")
@Select("select * from tb_user where id=#{user.id}")
public User select4User(Map<String,Object> param);
@CachePut(key = "#p0")
@Update("update user set account=#{name} where id=#{id}")
void updataById(@Param("id") Integer id,@Param("name")String name);
//如果指定为 true,则方法调用后将立即清空所有缓存
@CacheEvict(key ="#p0",allEntries=true)
@Delete("delete from user where id=#{id}")
void deleteById(@Param("id")String id);
}
2、controller层做缓存
@Autowired
private StringRedisTemplate stringRedisTemplate; //redis在controller层做缓存
/**
* redis做缓存
* @return
*/
@RequestMapping("/redisHandler")
public String redisHandler(){
stringRedisTemplate.opsForValue().set("k5", "Springboot redis");
return stringRedisTemplate.opsForValue().get("k5");
}