Official account: Java Xiaokaxiu, website: Javaxks.com

Author :CS wins you, link: blog.csdn.net/m0_37922192…

Note: the use of annotations on the interface brush function, very high, this article for reference only

First, technical points: basic knowledge of Springboot, redis basic operation,

First, write an annotation class:

 
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
 * @date2018/9/10 15:52 * /
 
@Retention(RUNTIME)
@Target(METHOD)
public @interface AccessLimit {
 
    int seconds(a);
    int maxCount(a);
    boolean needLogin(a)default true;
}
Copy the code

Then it is implemented in the 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
 * @date2018/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 {
 
        // Determine whether the request is a method request
        if(handler instanceof HandlerMethod){
 
            HandlerMethod hm = (HandlerMethod) handler;
 
            // Get the annotation in the method to see if it exists
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null) {return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean login = accessLimit.needLogin();
            String key = request.getRequestURI();
            // If you need to log in
            if(login){
                // Get the login session to judge
                / /...
                key+=""+"1";  // This assumes that the user is 1, and the project is a dynamically acquired userId
            }
 
            // Get the number of user visits from Redis
            AccessKey ak = AccessKey.withExpire(seconds);
            Integer count = redisService.get(ak,key,Integer.class);
            if(count == null) {// First visit
                redisService.set(ak,key,1);
            }else if(count < maxCount){
                / / 1
                redisService.incr(ak,key);
            }else{
                // The number of accesses exceeded
                render(response,CodeMsg.ACCESS_LIMIT_REACHED); // CodeMsg is a return parameter
                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(); }}Copy the code

Then register the Interceptor with 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
 * @date2018/9/10 therefore * /
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
 
    @Autowired
    private FangshuaInterceptor interceptor;
 
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor); }}Copy the code

Then add annotations to 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
 * @date2018/9/10 15:49 * /
 
@Controller
public class FangshuaController {
 
    @AccessLimit(seconds=5, maxCount=5, needLogin=true)
    @RequestMapping("/fangshua")
    @ResponseBody
    public Result<String> fangshua(a){
 
 
        return Result.success("Request successful");
 
    }
Copy the code

This article refers to the teaching of other videos, hoping to help more people who love it industry.