Custom annotation + interceptor project code optimization

Custom advantage annotation + interceptor

Rights or similar user interface to limiting demand, but not all of the operations or interface needs. You can use filters or interceptors, but this must be coupled with all the methods in the configuration file or use wildcards.
It is possible to use a relatively simple and flexible way: using custom annotation plus Spring interceptors to achieve.

Write the sample

For example, we now want to be the interface of counter limiting, just like this, you can add a comment. Defined as per seconds seconds, the maximum capacity maxCount.

@AccessLimit(seconds=5, maxCount=5)
@RequestMapping(value="/path", method=RequestMethod.GET)
@ResponseBody
public Result<String> getMiaoshaPath(...) {
    // 业务逻辑代码
}

Notes are defined as follows:

@Retention(RUNTIME)
@Target(METHOD)
public @interface AccessLimit {
    int seconds();
    int maxCount();
}

With interceptor uses the annotations take effect:

@Service
public class AccessInterceptor  extends HandlerInterceptorAdapter{

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(handler instanceof HandlerMethod) {
            MiaoshaUser user = getUser(request, response);
            UserContext.setUser(user);
            HandlerMethod hm = (HandlerMethod)handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null) {
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            String key = request.getRequestURI();
            Integer count = redisService.get(key);
            if(count  == null) {
                // 定义一个seconds有效期的key
                redisService.set(key, 1, seconds);
            }else if(count < maxCount) {
                redisService.incr(key);
            }else {
                return false;
            }
        }
        return true;
    }
}

Finally, my experience is limited to a limited level, readers are welcome valuable suggestions and comments on the text of the opinion. If you want to get more resources or want to learn more and exchange of technology enthusiasts together, I can focus on the public number "whole food engineer Xiaohui," replies the background Keywords receive learning materials, into the front and back end technology exchange group and a programmer sideline group. Programmers also can join the group sideline Q group: 735 764 906 with the exchange.

Heck, if my card lost.  Micro-letter search for "whole food engineer Xiaohui," I can still find

Guess you like

Origin www.cnblogs.com/mseddl/p/11582194.html