1、添加依赖
在pom.xml中添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置Application.yml文件
2.1、配置链接信息
- 单机配置
spring: ... redis: host: redis5OS port: 6379 password: 123
- 连接Redis高可用集群
spring: ... redis: sentinel: master: mymaster nodes: sentinel1:6379,sentinel2:6379,sentinel3:6379
2.2、配置缓存类型
spring:
...
cache:
# 指定当前业务所使用的缓存类型
type: redis
# 指定当前应用所使用的缓存区域名称
cache-names: realTimeCache
3、实体类序列化
@Data
public class Teacher implements Serializable {
private Integer id;
private String name;
private int age;
}
4、为Application.java添加注解
在Application类上添@EnableCaching
注解
package com.blairscott;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching // 开启当前应用的缓存
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5、使用注解方式访问Redis
-
通过缓存获取,若获取不到,则通过数据库获取并插入缓存
@Cacheable(value = "realTimeCache", key = "'teacher_' + #id") @Override public Teacher findById(String id) { return dao.findById(id); }
属性 说明 value 指定当前应用所使用的缓存区域名称,在2.2中设置过。 key 缓存的key,可以通过 #形参 的方式获取方法形参,并通过 + 拼接字符串 -
修改数据库并刷新Redis
@CacheEvict(value = "realTimeCache", allEntries = true) @Override public void addTeacher(Teacher teacher) { dao.insertTeacher(teacher); }
6、使用API访问Redis
@Service
public class TeacherServiceImpl implements TeacherService {
...
@Autowired
private TeacherDao dao;
// 注入RedisTemplate
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Override
public int countTeacherName(String name) {
// 获取Redis操作对象
BoundValueOperations<Object, Object> ops = redisTemplate.boundValueOps("count");
// 从redis中获取指定key的value
Object count = ops.get();
if (count == null) {
// 从数据库中获取数据
count = dao.countByName(name);
// 将查询结果存放Redis中,并指定过期时限
ops.set(count, 10, TimeUnit.SECONDS);
}
return (Integer) count;
}
}
7、Redis在高并发情况下可能存在的问题
7.1、缓存穿透
-
说明
当存DB中查询结果为null时,有可能会出现缓存穿透问题。所有请求都会穿过Redis,直接查询DB,造成数据库压力。 -
解决方案
当查询到为null时,为这些null的结果赋予一个默认值,并存入Redis中。
7.2、缓存雪崩
-
说明
当缓存中的某些缓存在同一很短的时段内几乎同时到期,此时就可能会引发缓存雪崩。此时,大量地访问这些缓存的请求由于未能从Redis中获取数据而向数据库发出请求,造成数据库压力。 -
解决方案
没有明确的解决方案,只能提前规划好缓存的到期时间,不要让Redis中的数据在一个很短的时间内同时到期。
7.3、热点缓存
-
说明
当某一个缓存的有效期到达时,同时,大量的访问请求正好过来,可能会引发热点缓存。 -
解决方案
使用双重检查锁机制。@Override public int countTeacherName(String name) { BoundValueOperations<Object, Object> ops = redisTemplate.boundValueOps("count"); // 双重检查锁机制 Object count = ops.get(); if (count == null) { synchronized (this) { count = ops.get(); if (count == null) { count = dao.countByName(name); ops.set(count, 10, TimeUnit.SECONDS); } } } return (Integer) count; }