当前位置: 首页 > news >正文

Springboot 在 redis 中使用 BloomFilter 布隆过滤器机制

一、导入SpringBoot依赖

pom.xml文件中,引入Spring Boot和Redis相关依赖

<!-- Google Guava 使用google的guava布隆过滤器实现--><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>30.1-jre</version></dependency>

二、配置布隆过滤器

创建一个布隆过滤器配置类BloomFilterConfig:

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class BloomFilterConfig {@Beanpublic BloomFilter<String> bloomFilter() {return BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), 1000000, 0.01);}
}

三、实现缓存服务

创建一个BloomFilterController。使用布隆过滤器判断数据是否存在,从而避免缓存穿透:

package com.springboot3.test;import com.google.common.hash.BloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;@RestController
@Controller
public class BloomFilterController {@Autowiredprivate BloomFilter bloomFilter;@Autowiredprivate RedisTemplate redisTemplate;@GetMapping("/cache/{key}")public String getCacheValue(@PathVariable String key) {boolean result = bloomFilter.mightContain(key);if(result==true){Object obj = redisTemplate.opsForValue().get(key);return obj.toString();}return "Cache miss, and the key does not exist in database.";}@GetMapping("/cache/{key}/{value}")public String setCacheValue(@PathVariable String key, @PathVariable String value) {bloomFilter.put(key);return "Cache set successfully.";}}

四、测试

向里面添加元素

 获取元素

http://www.lryc.cn/news/124023.html

相关文章:

  • 什么是管理的本质?
  • 02:STM32--EXTI外部中断
  • CLickhouse核心特性
  • 如何运用小程序技术闭环运营链路?
  • 使用chatGPT-4 畅聊量子物理学(二)
  • 读《Flask Web开发实战》(狼书)笔记 | 第1、2章
  • Tomcat+Http+Servlet
  • Leaflet入门,Leaflet如何实现vue双向绑定数据添加到图片标记物到地图上,动态根据vue数据更新到地图上以及鼠标经过标记物显示提示框
  • C++设计模式结构型之代理模式
  • 使用PHP实现实时聊天功能的匿名聊天与加密传输
  • Maven 基础之依赖管理、范围、传递、冲突
  • Python jupyter lab 设置
  • 水库大坝安全监测系统实施方案
  • GloVe、子词嵌入、BPE字节对编码、BERT相关知识(第十四次组会)
  • Debian10:安装PHPVirtualBox
  • RANSAC算法
  • 考研408 | 【计算机网络】 传输层
  • Redis_缓存3_缓存异常(数据不一致、雪崩、击穿、穿透)
  • 谁能讲清楚Spark之与MapReduce的对比
  • Android自定义侧滑Item
  • c++11 标准模板(STL)(std::basic_stringbuf)(三)
  • Nodejs 第九章(模块化)
  • shell之正则表达式及三剑客grep命令
  • LeetCode 热题 100 JavaScript--33. 搜索旋转排序数组
  • 并发编程 - 线程池中的常见面试题
  • 将多个单独的 Excel 文件合并成一个,并添加标题行
  • VPN pptp和l2tp协议破解
  • 4.3、Flink任务怎样读取Kafka中的数据
  • C语言实例_和校验算法
  • 安全加密框架图——Oracle安全开发者