引入 整合redis测试 StringRedisTemplate
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
//application.yml
spring
redis:
host: 192.168.56.10
port: 6379
测试
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
public void teststringRedisTemplate(){
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//保存到redis // UUID.randomUUID().toString());一个自动生成主键的方法。全局唯一标识符
ops.set(hello,world_+ UUID.randomUUID().toString());
//查询
String hello = ops.get(hello);
System.out.println(保存的是+hello);
}
应用
public Map<String, List<Catelog2Vo>> getCatalogJson(){
//给缓存放的是接送字符串 拿出来也要逆转出来 能用的子对象类型 序列化 反序列化
//加入缓存逻辑 缓存存的数据是json字符串 json 跨语言跨平台兼容的
String catalogJson = redisTemplate.opsForValue().get(catalogJson);
//如果 为空或者没有 去查数据库
if (StringUtils.isEmpty(catalogJson)){
Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
//转换json 保存
String s = JSON.toJSONString(catalogJsonFromDb);
// 查到的数据放到缓存 j将查出来对象转换成json 存入缓存中
redisTemplate.opsForValue().set(catalogJson,s);
}
//转为指定对象 用JSON.parseObject 传入要转换的 以及转换的类型TypeReference受到保护接上{}
Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
return result;}
压力测试出的内存泄露及解决
//去除lettuce-core 引用jedis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
缓存使用-缓存击穿、穿透、雪崩
- 1.空结果缓存:解决缓存穿透问题
- 2.设置过期时间(加随机值):解决雪崩问题
- 3.解决缓存击穿:加锁
public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
//todo 本地锁
synchronized (this){
//得到所之后 去缓存中确定一次,如果没有继续查询
String catalogJson = redisTemplate.opsForValue().get(catalogJson);
if (!StringUtils.isEmpty(catalogJson)){
//不为空直接返回
return result;
}
System.out.println(查询数据库);
}
高并发下查询两次数据库,而非一次,是应为放入缓存需要一定时间, 加锁解锁之后第二个线程未能查到缓存中有,所以又查了一遍数据库, 解决方法,放入缓存而非在加锁时候放缓存,要在第一次查询时候就放缓存