通过过滤器实现简单的限流操作

1@Component 2@Slf4j 3public class MyFilter implements Filter { 4 5 6 private static volatile long startTime = System.currentTimeMillis(); 7 8 // 时间窗口 9 private static final long windowTime = 1000L; 10 11 // 1s只能通过200个请求 12 private static final int door = 200; 13 14 private static final AtomicInteger bear = new AtomicInteger(0); 15 16 @Override 17 public void init(FilterConfig filterConfig) throws ServletException { 18 Filter.super.init(filterConfig); 19 } 20 21 @Override 22 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 23 int count = bear.incrementAndGet(); 24 if (count == 1) { 25 startTime = System.currentTimeMillis(); 26 } 27 long now = System.currentTimeMillis(); 28 log.info("拦截了请求, count: {}", count); 29 log.info("时间窗口: {}ms, count: {}", (now - startTime), count); 30 if (now - startTime <= windowTime) { 31 if (count > door) { // 超过了阈值 32 // 限流操作 33 log.info("限流, 拦截了请求, count: {}", count); 34 HttpServletResponse response = (HttpServletResponse) servletResponse; 35 response.setStatus(HttpStatus.OK.value()); 36 response.setContentType(MediaType.APPLICATION_JSON_VALUE); 37 response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); 38 response.getWriter().print(JSONUtil.toJsonStr(Result.error("402", "接口请求过于频繁"))); 39 return; 40 } 41 } else { 42 startTime = System.currentTimeMillis(); 43 bear.set(1); 44 } 45 HttpServletRequest request = (HttpServletRequest) servletRequest; 46 filterChain.doFilter(servletRequest, servletResponse); 47 log.info("接口请求的路径:{}", request.getServletPath()); 48 } 49 50 @Override 51 public void destroy() { 52 Filter.super.destroy(); 53 } 54 55}
点赞
收藏

评论区

加载中...

相关推荐

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

springboot2之优雅处理返回值

前言最近项目组有个老项目要进行前后端分离改造,应前端同学的要求,其后端提供的返回值格式需形如{"status":0,"message":"success","data":{}}方便前端数据处理。要实现前端同学这个需求,其实也挺简单的,

FLV文件格式

1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  

Prometheus监控学习笔记之PromQL简单示例

0x00简单的时间序列选择返回度量指标http_requests_total的所有时间序列样本数据:http_requests_total返回度量指标名称为http_requests_total,标签分别是job"apiserver",handler"/api/comments"

mysql中时间比较的实现

MySql中时间比较的实现unix\_timestamp()unix\_timestamp函数可以接受一个参数,也可以不使用参数。它的返回值是一个无符号的整数。不使用参数,它返回自1970年1月1日0时0分0秒到现在所经过的秒数,如果使用参数,参数的类型为时间类型或者时间类型的字符串表示,则是从1970010100:00:0