自定义注解+拦截器优化项目代码
生活随笔
收集整理的這篇文章主要介紹了
自定义注解+拦截器优化项目代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自定義注解+攔截器的優勢
類似用戶權限或者接口限流的需求,但并不是所有操作或者接口需要。可以使用過濾器或者攔截器,但這樣就必須在配置文件里加上所有方法或者使用通配符。
所以可以采用一種比較簡單靈活的方式:采用自定義注解加Spring攔截器來實現。
編寫示例
例如我們現在要做個接口的計數器限流,只需要像下面這樣,加上一個注解即可。定義為每seconds秒內,最大訪問量maxCount。
@AccessLimit(seconds=5, maxCount=5) @RequestMapping(value="/path", method=RequestMethod.GET) @ResponseBody public Result<String> getMiaoshaPath(...) {// 業務邏輯代碼 }注解定義如下:
@Retention(RUNTIME) @Target(METHOD) public @interface AccessLimit {int seconds();int maxCount(); }配合攔截器使用,使注解生效:
@Service public class AccessInterceptor extends HandlerInterceptorAdapter{@AutowiredRedisService redisService;@Overridepublic 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有效期的keyredisService.set(key, 1, seconds);}else if(count < maxCount) {redisService.incr(key);}else {return false;}}return true;} }總結
以上是生活随笔為你收集整理的自定义注解+拦截器优化项目代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uni-app学习日记1
- 下一篇: 创业前期怎么做个简单易行的计划?