Spring Boot project API interface anti-brush

  • First class is to write a comment

  • Interceptor implemented

  • Sign in to springboot

  • Add comments in the Controller

  • Description: Use annotations on the way the interface anti brush function, a very tall, this article is only a reference, technical points: basic knowledge of springboot, redis basic operations,

    The first is to write a comment like:

  • import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    
    import static java.lang.annotation.ElementType.METHOD;
    import static java.lang.annotation.RetentionPolicy.RUNTIME;
    
    /**
     * @author yhq
     * @date 2018/9/10 15:52
     */
    
    @Retention(RUNTIME)
    @Target(METHOD)
    public @interface AccessLimit {
    
        int seconds();
        int maxCount();
        boolean needLogin()default true;
    }

    Interceptor

    import com.alibaba.fastjson.JSON;
    import com.example.demo.action.AccessLimit;
    import com.example.demo.redis.RedisService;
    import com.example.demo.result.CodeMsg;
    import com.example.demo.result.Result;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.OutputStream;
    
    /**
     * @author yhq
     * @date 2018/9/10 16:05
     */
    
    
    @Component
    public class FangshuaInterceptor extends HandlerInterceptorAdapter {
    
        @Autowired
        private RedisService redisService;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            //判断请求是否属于方法的请求
            if(handler instanceof HandlerMethod){
    
                HandlerMethod hm = (HandlerMethod) handler;
    
                //Acquiring annotation methods to see if the notes 
                AccessLimit accessLimit = hm.getMethodAnnotation (AccessLimit. Class );
                 IF (accessLimit == null ) {
                     return  to true ; 
                } 
                int seconds The = accessLimit.seconds ();
                 int maxCount = accessLimit.maxCount ();
                 Boolean Login = accessLimit.needLogin (); 
                String Key = Request.getRequestURI ();
                 // if desired log 
                IF (Login) {
                     // Get the determination login session
                     //..... 
                    Key + = "" + "1";   // assumed that the user is 1, the program is dynamically acquired the userId 
                } 
    
                // number of times the user accessed from redis acquired in 
                the AccessKey AK = AccessKey.withExpire (seconds The); 
                COUNT Integer = redisService.get (AK, Key, Integer. class );
                 IF (COUNT == null ) {
                     // first access 
                    redisService.set (AK, Key,. 1 ); 
                } the else  IF (COUNT < maxCount) {
                     // add. 1 
                    redisService.incr (AK, Key); 
                } the else{
                    //超出访问次数
                    render(response,CodeMsg.ACCESS_LIMIT_REACHED); //这里的CodeMsg是一个返回参数
                    return false;
                }
            }
    
            return true;
    
        }
        private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
            response.setContentType("application/json;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            String str  = JSON.toJSONString(Result.error(cm));
            out.write(str.getBytes("UTF-8"));
            out.flush();
            out.close();
        }
    }

    Sign in to springboot

    import com.example.demo.ExceptionHander.FangshuaInterceptor;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * @author yhq
     * @date 2018/9/10 15:58
     */
    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Autowired
        private FangshuaInterceptor interceptor;
    
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(interceptor);
        }
    }

    Add comments in the Controller

     
  • import com.example.demo.result.Result;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * @author yhq
     * @date 2018/9/10 15:49
     */
    
    @Controller
    public class FangshuaController {
    
        @AccessLimit(seconds=5, maxCount=5, needLogin=true)
        @RequestMapping("/fangshua")
        @ResponseBody
        public Result<String> fangshua(){
    
    
            returnResult.success ( "request was successful" ); 
    
        }

    Related reference: https://www.jianshu.com/p/364a6f466a2a

  •  

     

 

Guess you like

Origin www.cnblogs.com/leeego-123/p/11940464.html