我们需要根据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
}

我使用了redis缓存访问次数,并且设置自增1,其实用静态map也可以。

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

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

    原文:http://www.cnblogs.com/xiaoyangjia/p/3762150.html?utm_source=tuicool 我们需要根据IP去限制用户单位时间的访问次数,防止刷手机 ...

  2. springMVC基于注解的控制器

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

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

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

  4. springmvc 自定义注解 以及自定义注解的解析

    1,自定义注解名字 @Target({ElementType.TYPE, ElementType.METHOD})   //类名或方法上@Retention(RetentionPolicy.RUNTI ...

  5. springMVC自定义注解实现用户行为验证

    最近在进行项目开发的时候需要对接口做Session验证 1.自定义一个注解@AuthCheckAnnotation @Documented @Target(ElementType.METHOD) @I ...

  6. springmvc 自定义注解

    1. 自定义一个注解 @Documented //文档生成时,该注解将被包含在javadoc中,可去掉 @Target(ElementType.METHOD)//目标是方法 @Retention(Re ...

  7. Spring boot 自定义注解标签记录系统访问日志

    package io.renren.common.annotation; import java.lang.annotation.Documented; import java.lang.annota ...

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

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

  9. 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s

     1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2  spring-mv ...

随机推荐

  1. 十二.HTTPS网站安全访问实践

    期中集群架构-第十二章-HTTPS安全证书访问连接实践配置========================================= 01:网络安全涉及的问题: ①. 网络安全问题-数据机密性 ...

  2. RabbitMQ可靠性投递及高可用集群

    可靠性投递: 首先需要明确,效率与可靠性是无法兼得的,如果要保证每一个环节都成功,势必会对消息的收发效率造成影响.如果是一些业务实时一致性要求不是特别高的场合,可以牺牲一些可靠性来换取效率. 要保证消 ...

  3. python3 字典(dictionary)(一)

    一.定义:是另一种可变容器模型,可存储任意类型对象:(也被称为关联数组或哈希表:存储的数据是没有顺序的) 语法为: d = {key1 : value1, key2 : value2 } #----- ...

  4. python3 基础语法(一)

    一.标识符: 第一个字符必须是字母表中字母或下划线 “_” . 例如: #!/usr/bin/env python #coding=utf-8 a = 3 _aa = 3 a3 = 3 _aa3 = ...

  5. Centos查看系统CPU个数、核心数、线程数

    1.查看 CPU 物理个数 grep 'physical id' /proc/cpuinfo | sort -u | wc -l 2.查看 CPU 核心数量 grep 'core id' /proc/ ...

  6. std::array中的std::get<n>()

    模板函数std::get<n>()是一个辅助函数,它能够获取到容器的第 n 个元素.模板参数的实参必须是一个在编译时可以确定的常量表达式,编译时会对它检查. get<n>()模 ...

  7. IDEA安装ini4idea插件

    参见https://blog.csdn.net/lintianlin/article/details/80050309

  8. 在使用EF时,想要比较字符串类型的日期时

    原文地址(https://blog.csdn.net/yangxinyue315/article/details/44960895) 在使用EF时,想要比较字符串类型的日期时 在使用EF时,想要比较字 ...

  9. zabbix环境安装搭建

    一.Zabbix简介 zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.zabbix由zabbix server与可选组件zabbix agent两部分组成. ...

  10. PHP服务器时差8小时的解决办法

    PHP服务器时差8小时的解决办法 <?php date_default_timezone_set('Asia/Shanghai');  echo date("Y-m-d")? ...