1:创建IdempotentFilter过滤器,项目是spring boot工程
public class IdempotentFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = request.getParameter("token");
HttpSession httpSession = request.getSession(false);
Object value = httpSession.getAttribute(token);
if(value != null){
throw new ServletException("幂等性校验");
}
httpSession.setAttribute(token,token);
try{
filterChain.doFilter(request,response);
}finally {
httpSession.removeAttribute(token);
}
}
}
2:流程分析
请求第一次过来->获取参数token(可以是请求头上绑定任何参数)
->把token值放在session上(可以放在redis 或中间件上都可以)->
如果获取值说明不是第一次请求-> 直接拒绝