原文:http://www.cnblogs.com/xiaoyangjia/p/3762150.html?utm_source=tuicool

我们需要根据IP去限制用户单位时间的访问次数,防止刷手机验证码,屏蔽注册机等,使用注解就非常灵活了

1 定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
//最高优先级
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
*
* 允许访问的次数,默认值MAX_VALUE
*/
int count() default Integer.MAX_VALUE; /**
*
* 时间段,单位为毫秒,默认值一分钟
*/
long time() default 60000;
}

 2 实现注解

@Aspect
@Component
public class RequestLimitContract {
private static final Logger logger = LoggerFactory.getLogger("RequestLimitLogger");
@Autowired
private RedisTemplate<String, String> redisTemplate; @Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException { try {
Object[] args = joinPoint.getArgs();
HttpServletRequest request = null;
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof HttpServletRequest) {
request = (HttpServletRequest) args[i];
break;
}
}
if (request == null) {
throw new RequestLimitException("方法中缺失HttpServletRequest参数");
}
String ip = HttpRequestUtil.getIpAddr(request);
String url = request.getRequestURL().toString();
String key = "req_limit_".concat(url).concat(ip);
long count = redisTemplate.opsForValue().increment(key, 1);
if (count == 1) {
redisTemplate.expire(key, limit.time(), TimeUnit.MILLISECONDS);
}
if (count > limit.count()) {
logger.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
throw new RequestLimitException();
}
} catch (RequestLimitException e) {
throw e;
} catch (Exception e) {
logger.error("发生异常: ", e);
}
}
}

3 自定义Exception

public class RequestLimitException extends Exception {
private static final long serialVersionUID = 1364225358754654702L; public RequestLimitException() {
super("HTTP请求超出设定的限制");
} public RequestLimitException(String message) {
super(message);
} }

4 在Controller中使用

@RequestLimit(count=100,time=60000)
@RequestMapping("/test")
public String test(HttpServletRequest request, ModelMap modelMap) {
//TODO
}

[SpringMVC+redis]自定义aop注解实现控制器访问次数限制的更多相关文章

  1. [SpringMVC]自定义注解实现控制器访问次数限制

    我们需要根据IP去限制用户单位时间的访问次数,防止刷手机验证码,屏蔽注册机等,使用注解就非常灵活了 1 定义注解 @Retention(RetentionPolicy.RUNTIME) @Target ...

  2. SpringMVC中的常用注解

    RequestParam 作用: 用于  将请求参数区数据  映射到  功能处理方法的参数上. 属性: value  请求参数中的名称 required   请求参数中是否必须提供此参数. 默认值: ...

  3. Spring aop注解失效

    问题 在spring 中使用 @Transactional . @Cacheable 或 自定义 AOP 注解时,对象内部方法中调用该对象的其他使用aop机制的方法会失效. @Transactiona ...

  4. 使用Redis+自定义注解实现接口防刷

    最近开发了一个功能,需要发送短信验证码鉴权,考虑到短信服务需要收费,因此对此接口做了防刷处理,实现方式主要是Redis+自定义注解(需要导入Redis的相关依赖,完成Redis的相关配置,gs代码,这 ...

  5. SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解

    SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解 博客分类: 跟开涛学SpringMVC   6.6.2.@RequestParam绑定单个请求参数值 @RequestParam用于 ...

  6. SpringMVC传统风格控制器和基于注解的控制器

    SpringMVC的DispatcherServlet 之前说过springMVC是使用Servlet作为控制器,就是这个用于调度的DispatcherServlet了.这个是servlet,可以根据 ...

  7. 【spring springmvc】springmvc使用注解声明控制器与请求映射

    目录 概述 壹:注解说明 贰:实现注解声明控制器与请求映射 一:使用controller 二:配置包扫描与视图解析器 1.配置包扫描 2.配置试图解析器 三:配置部署描述符 1.读取spring-mv ...

  8. [译]SpringMVC自定义验证注解(SpringMVC custom validation annotations)

    在基于SpringMVC框架的开发中,我们经常要对用户提交的字段进行合法性验证,比如整数类型的字段有个范围约束,我们会用@Range(min=1, max=4).在实际应用开发中,我们经常碰到一些自己 ...

  9. springMVC基于注解的控制器

    springMVC基于注解的控制器 springMVC基于注解的控制器的优点有两个: 1.控制器可以处理多个动作,这就允许将相关操作写在一个类中. 2.控制器的请求映射不需要存储在配置文件中.使用re ...

随机推荐

  1. 【Python实例二】之前期准备:Windows下的BeautifulSoup安装

    前言 一直久闻Python的爬虫很高效,而且操作便捷,因此决定开始练习爬虫的相关内容. 首先尝试的是Python的爬虫利器之一:BeautifulSoup.(这名字听起来就有种想要去探究的兴趣.... ...

  2. hashlib,suprocess,configparser模块

    十 hashlib模块 1.什么叫hash:hash是一种算法,该算法接受传入的内容,经过运算得到一串hash值 2.hash值的特点是: 2.1 只要传入的内容一样,得到的hash值必然一样==== ...

  3. LeetCode 4 :Majority Element

    problem:Given an array of size n, find the majority element. The majority element is the element tha ...

  4. go开发

    我开发中一直用这一段 //for debuggingfunc printPretty(v interface{}, mark string) (err error) { fmt.Printf(&quo ...

  5. logging模块的使用

    # -*- coding: utf-8 -*- import os import time import logging import sys log_dir1=os.path.join(os.pat ...

  6. 【洛谷】xht模拟赛 题解

    前言 大家期待已久并没有的题解终于来啦~ 这次的T1和HAOI2016撞题了...深表歉意...表示自己真的不知情... 天下的水题总是水得相似,神题各有各的神法.--<安娜·卡列妮娜> ...

  7. 解析gtest框架运行机制

    前言 Google test是一款开源的白盒单元测试框架,据说目前在Google内部已在几千个项目中应用了基于该框架的白盒测试. 最近的工作是在搞一个基于gtest框架搭建的自动化白盒测试项目,该项目 ...

  8. 让button居中显示的的标签

    <center> <input type="button" class="buttoncls" style="width:80px& ...

  9. easyui时间控件用js实时获取选定的时间的取法

    easyui时间控件用js实时获取选定的时间的取法var   datetime=$("#id").datetimebox("getValue");不能用 $(& ...

  10. ZOJ-3822

    Domination Time Limit: 8 Seconds      Memory Limit: 131072 KB      Special Judge Edward is the headm ...