java

spring处理幂等性filter

2024-05-22  本文已影响0人  左洁

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 或中间件上都可以)->
如果获取值说明不是第一次请求-> 直接拒绝

github代码

上一篇 下一篇

猜你喜欢

热点阅读