package com.zhaoyang.controller;
import com.zhaoyang.domain.Person;
import com.zhaoyang.service.PersonService;
import com.zhaoyang.util.BloomFilterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
//缓存穿透:在Controller中查询数据时,先根据请求参数进行Bloom Filter的过滤
@RestController
public class RC2 {
@Autowired
private PersonService personService;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@GetMapping("/person2/{id}")
public Person getUserById(@PathVariable String id){
//先从布隆过滤器中判断此id是否存在
if(BloomFilterUtil.mightContain(id)){
return null;
}
//查询缓存数据
Person person = (Person) redisTemplate.opsForValue().get(id);
if(person == null){
//查询数据库
person = personService.getById(id);
if(person != null){
//将查询到的数据加入缓存
redisTemplate.opsForValue().set(id, person, 300, TimeUnit.SECONDS);
}else{
//查询结果为空,将请求记录下来,并在布隆过滤器中添加
BloomFilterUtil.add(id);
}
}
return person;
}
}