【3】编辑配置类
@Slf4j@Configurationpublic class BloomFilterConfig implements InitializingBean{@Autowiredprivate PmsProductService productService;@Autowiredprivate RedisTemplate template;@Beanpublic BloomFilterHelper<String> initBloomFilterHelper() {return new BloomFilterHelper<>((Funnel<String>) (from, into) -> into.putString(from, Charsets.UTF_8).putString(from, Charsets.UTF_8), 1000000, 0.01);}// 布隆过滤器bean注入@Beanpublic BloomRedisService bloomRedisService(){BloomRedisService bloomRedisService = new BloomRedisService();bloomRedisService.setBloomFilterHelper(initBloomFilterHelper());bloomRedisService.setRedisTemplate(template);return bloomRedisService;}@Overridepublic void afterPropertiesSet() throws Exception {List<Long> list = productService.getAllProductId();log.info("加载产品到布隆过滤器当中,size:{}",list.size());if(!CollectionUtils.isEmpty(list)){list.stream().forEach(item->{//LocalBloomFilter.put(item);bloomRedisService().addByBloomFilter(RedisKeyPrefixConst.PRODUCT_REDIS_BLOOM_FILTER,item+"");});}}}【4】构建布隆过滤器的拦截器
//拦截器,所有需要查看商品详情的请求必须先过布隆过滤器@Slf4jpublic class BloomFilterInterceptor implements HandlerInterceptor {@Autowiredprivate BloomRedisService bloomRedisService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String currentUrl = request.getRequestURI();PathMatcher matcher = new AntPathMatcher();//解析出pathvariableMap<String, String> pathVariable = matcher.extractUriTemplateVariables("/pms/productInfo/{id}", currentUrl);//布隆过滤器存储在redis中if(bloomRedisService.includeByBloomFilter(RedisKeyPrefixConst.PRODUCT_REDIS_BLOOM_FILTER,pathVariable.get("id"))){return true;}/** 不在布隆过滤器当中,直接返回验证失败* 设置响应头*/response.setHeader("Content-Type","application/json");response.setCharacterEncoding("UTF-8");String result = new ObjectMapper().writeValueAsString(CommonResult.validateFailed("产品不存在!"));response.getWriter().print(result);return false;}}【5】将拦截器注册进SpringMVC中
@Configurationpublic class IntercepterConfiguration implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {//注册拦截器registry.addInterceptor(authInterceptorHandler()).addPathPatterns("/pms/productInfo/**");}@Beanpublic BloomFilterInterceptor authInterceptorHandler(){return new BloomFilterInterceptor();}}【Redis实现布隆过滤器解析】
经验总结扩展阅读
- 18 基于.NetCore开发博客项目 StarBlog - 实现本地Typora文章打包上传
- 广州南怎么换乘
- 深入理解AQS--jdk层面管程实现【管程详解的补充】
- Go实现优雅关机与平滑重启
- [s905l3]性价比神机mgv3000全网首拆,刷armbian实现更多价值!
- 2 Libgdx游戏开发——接水滴游戏实现
- 带样式 JSP实现登录删除添加星座等
- 结合springboot实现,这里对接的是easy版本,工具用的是IDEA,WebStrom 支付宝沙箱服务
- Asp-Net-Core开发笔记:集成Hangfire实现异步任务队列和定时任务
- Skywalking Swck Agent注入实现分析