一、API防刷限流:
API接口限流,旨在预防用户过度频繁地访问特定接口,以及抵御潜在的恶意攻击行为,这些行为可能导致后端服务器承受过高的负载,进而引发内存资源紧张。为了有效缓解服务器面临的压力,确保服务的稳定性和可用性,对接口实施防刷限流措施显得尤为重要。
实现思路:
在Spring Boot应用中结合Redis实现后端拦截前端请求的功能,具体流程如下:后端系统拦截来自前端的每一个请求,使用请求的IP地址加上请求的具体信息(如接口路径、请求方法等)作为key,在Redis中查询对应的value值。若查询结果为空,表示这是该IP对该请求的首次访问,系统将继续执行后续操作,并在Redis中为该key设置一个初始的访问次数(如1)及过期时间。若查询结果不为空,则解析value值以获取当前的访问次数,并与预设的限定值进行比较。若访问次数超过限定值,则立即向前端返回提示信息,并终止执行后续操作;若未超过限定值,则更新Redis中的访问次数,并继续执行后续操作。
二、代码示例
第一步 创建AccessLimitIntercept类,编写实现功能的核心代码。
package com.example.mybatisdemo.config;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
@Component
public class AccessLimitIntercept implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
//限定访问次数
private int count=5;
//访问时间
private int time=10;
private final static String localIp = "127.0.0.1";
/**
* 获取ip地址
* @param request
* @return
*/
public static String getIp(HttpServletRequest request){
String ipAddress;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (localIp.equals(ipAddress)) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) {
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress = "";
}
return "0:0:0:0:0:0:0:1".equals(ipAddress) ? localIp : ipAddress;
}
/**
* 进入controller前的预处理
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String key=getIp(request)+request.getRequestURI();
Object value = redisTemplate.opsForValue().get(key);
// 获取redis的value
Integer valueTime=null;
//表示第一次访问
if(value==null)
{
//存放访问的次数,time表示时间, TimeUnit.SECONDS表示时间单位为秒
redisTemplate.opsForValue().set(key, 1, time, TimeUnit.SECONDS);
}
if(value!=null)
{
valueTime= (Integer) value;
if(valueTime<count)
{
//访问次数累加
redisTemplate.opsForValue().set(key, valueTime+1, time, TimeUnit.SECONDS);
}else {
output(response, "{\"code\":\"8002\",\"message\":\"请求过于频繁,请稍后再试\"}");
return false;
}
}
return true;
}
public void output(HttpServletResponse response, String msg) throws IOException {
response.setContentType("application/json;charset=UTF-8");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(msg.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ObjectUtils.isNotEmpty(outputStream)) {
outputStream.flush();
outputStream.close();
}
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
配置配置文件,将写好的拦截器配置到容器中
package com.example.mybatisdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 这里需要先将限流拦截器入住,不然无法获取到拦截器中的redistemplate
* @return
*/
@Bean
public AccessLimitIntercept getAccessLimitIntercept() {
return new AccessLimitIntercept();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getAccessLimitIntercept()).addPathPatterns("/**");
}
}
创建 controller 测试类
@RestController
public class AcessController {
@GetMapping("/test")
public String Testmethod()
{
String st="hello,you enter system";
System.out.println("成功访问到方法");
return st;
}
}
在浏览器访问 http://localhost:8080/test
连续点击测试