布隆过滤器检测元素是否存在的示例
下文笔者讲述java代码使用布隆过滤器的方法及示例分享,如下所示
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 布隆过滤器 -> redis -> mysql
* @autor java265.com
* @date 2024-01-18
*/
@Service
public class StudentServiceImpl implements StudentService {
public static final String CACHE_KEY = "student:";
@Autowired
private StudentMapper studentMapper;
@Autowired
private redisTemplate redisTemplate;
public void addstudent(student student){
int i = studentMapper.insertSelective(student);
if(i > 0) {
//到数据库里面,重新捞出新数据出来,做缓存
student=studentMapper.selectByPrimaryKey(student.getId());
//缓存key
String key=CACHE_KEY+student.getId();
//往mysql里面插入成功随后再从mysql查询出来,再插入redis
redisTemplate.opsForValue().set(key,student);
}
}
public student findstudentById(Integer studentId){
student student = null;
//缓存key的名称
String key=CACHE_KEY+studentId;
// 查询redis
student = (student) redisTemplate.opsForValue().get(key);
//redis没有,查询mysql
if(student==null) {
student=studentMapper.selectByPrimaryKey(studentId);
// mysql有,redis没有
if (student != null) {
// 把mysql捞到的数据写入redis
redisTemplate.opsForValue().set(key,student);
}
}
return student;
}
/**
* BloomFilter -> redis -> mysql
* 白名单:whites
*/
public student findStudentByIdWithBloomFilter (Integer studentId) {
student student = null;
String key = CACHE_KEY + studentId;
//布隆过滤器校验,无是绝对无,有是可能有
if(!checkWithBloomFilter("whites",key)) {
log.info("白名单无此顾客信息:{}",key);
return null;
}
//查询redis
student = (Student) redisTemplate.opsForValue().get(key);
//redis没有,查询mysql
if (student == null) {
student = studentMapper.selectByPrimaryKey(studentId);
// mysql有,redis没有
if (student != null) {
// 把mysql捞到的数据写入redis
redisTemplate.opsForValue().set(key, student);
}
}
return student;
}
/**
* 查询布隆过滤器中是否存在
*/
public boolean checkWithBloomFilter(String checkItem,String key) {
int hashValue = Math.abs(key.hashCode());
long index = (long) (hashValue % Math.pow(2, 32));
return redisTemplate.opsForValue().getBit(checkItem, index);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


