SpringBoot项目中使用filter做限流
前言》》防忘备忘录
1、有些时候需要对项目中的某个接口或者某些接口做一下访问次数的限制,防止用户无休止的访问请求,以便服务器腾出更多的资源去处理核心业务。
2、下面的代码以修改手机号的接口为例,进行了次数限制(以此类推,举一反三,其他业务可做类似的防刷限制)
3、相关代码如下
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @create 2020-05-22 15:40
*手机号码变更次数限制
*/
@Slf4j
@Order(1)
@Component
@RequiredArgsConstructor
public class CountLimitFilter extends OncePerRequestFilter {
private final RedisTemplate<String,Integer> redisTemplate;
// 允许调用的次数
@Value("${count.mobileCount:5}")
private Integer mobileCount;
// 时间段
@Value("${count.mobilePeriod:10}")
private Integer mobilePeriod;
// 需要做限流的api
public static final String MOBILE_UPDATE_URI = "/api/update/mobile";
public static final AntPathRequestMatcher mobileAntPathMatcher = new AntPathRequestMatcher(MOBILE_UPDATE_URI, "POST");
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// URI匹配
if (mobileAntPathMatcher.matches(request)){
log.error("我是手机更改: "+request.getRequestURI());
String name = obtainName(request);
String idCard = obtainIdCard(request);
if (StringUtils.isBlank(name) || StringUtils.isBlank(idCard)){
throw new ApiRuntimeException(ApiResponseEnums.NAME_AND_IDCARD_NOT_ALLOWED_BLANK);
}
// 此处为根据参数生成可以标识用户唯一的key,存入redis中
String key = CountUtil.countMobileKey(name,idCard);
Integer count = redisTemplate.boundValueOps(key).get();
if (count == null){
// 初次访问,设置一个初始值并设定过期时间
count = 0;
redisTemplate.boundValueOps(key).set(count);
redisTemplate.expire(key,mobilePeriod, TimeUnit.MINUTES);
}
if (count < avatarCount){
// 每访问一次接口更新一次对应的值,加1操作。
redisTemplate.boundValueOps(key).increment(1L);
}else {
/** 如果在过期时间段内请求次数超过了允许的次数,直接抛异常,不再往下执行。
* 其实真实等待时间是小于mobilePeriod的,先这么提示吧
*/
throw new ApiRuntimeException(ApiResponseEnums.EXCEEDING_FREQUENCY_LIMIT.getCode(),"手机号更新过于频繁,请"+mobilePeriod+"分钟后再试!");
}
}
filterChain.doFilter(request,response);
}
public String obtainName(HttpServletRequest request){
return request.getParameter("name");
}
public String obtainIdCard(HttpServletRequest request){
return request.getParameter("idCard");
}
}
小尾巴~~
只要有积累,就会有进步