1 获取对象数据
// 缓存击穿 案列 防止多人同时间访问数据库
private Goods getGoods(int id){
// 缓存对象
Goods goods = (Goods) redisTemplate.opsForValue().get("goods:" + id);
if (goods==null){
// 当不存在数据时 设置互斥锁
Boolean b = redisTemplate.opsForValue().setIfAbsent(RedisContent.REDIS_LOCK, 1);
if (b){
// 第一个人 设置成功查询数据
goods = service.selectGoodById(id);
// 缓冲数据 设置1天失效
redisTemplate.opsForValue().set("goods:" + id,goods,1, TimeUnit.DAYS);
// 释放锁
redisTemplate.delete(RedisContent.REDIS_LOCK);
}else {
try {
// 其它人等待2秒 然后重新调用方法 获取数据
Thread.sleep(2000);
getGoods(id);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 如果不为空 返回对象
return goods;
}
2 三级联动 缓存数据
@ResponseBody
@RequestMapping("getCityList")
public List<City> getCityList(int pid){
if (redisTemplate.hasKey("citys:"+pid)){
// 从缓存数据取值
return redisTemplate.opsForList().range("citys:"+pid,0,-1);
}else {
// 第一次调用方法获取数据
List<City> cities = service.listCity(pid);
redisTemplate.opsForList().rightPushAll("citys:"+pid,cities);
return cities;
}
}