原文: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. Flume的安装,配置及使用

    1,上传jar包 2,解压 3,改名 4,更改配置文件 将template文件重镜像 root@Ubuntu-1:/usr/local/apache-flume/conf# cat flume-env ...

  2. 【bzoj1010-toy】斜率优化入门模板

    dsy1010: [HNOI2008]玩具装箱 [题目描述] 有n个数,分成连续的若干段,每段(假设从第j个到第i个组成一段)的分数为 (X-L)^2,X为j-i+Sigma(Ck) i<=k& ...

  3. GitLab 密码重设

    内容全部来自: CSDN bisal GitLab 密码重设方法 假设注册邮箱为: abc@test.com 步骤 1) 登录 git 服务器 2) 执行: gitlab-rails console ...

  4. bzoj 1076 状压DP

    我们设w[i][s]为当前到第i关,手中的物品为s的时候,期望得分为多少,其中s为二进制表示每种物品是否存在. 那么就比较容易转移了w[i][s]=(w[i-1][s']+v[j]) *(1/k),其 ...

  5. [Leetcode Week8]Edit Distance

    Edit Distance 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/edit-distance/description/ Description ...

  6. UART硬件流控制信号的使用(图)DTR 【转】

    UART硬件流控制信号的使用(图) 转自:http://blog.163.com/zy_tommy/blog/static/86926777201321925451164/ 2013-03-19 14 ...

  7. mybatis插入值的时候返回对象的主键值

    mapping文件: <insert id="insert" parameterType="com.vimtech.bms.business.riskproject ...

  8. MatserDetail自动展开

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windo ...

  9. redis使用中的常见错误

    1.2016年12月17日  启动redis报错,错误信息如下: 解决办法:redis没有正常关闭(redis安装在虚拟机上,直接杀死了虚拟机进程) 导致redis.pid文件一直被锁定,重启redi ...

  10. js一段小代码(浏览器用alert,否则用console)

    (function(){ var root=this, isBrowserSide=false; if(typeof window !=="undefined" && ...