redis通过ip限制接口访问次数(用注解形式实现)

      近期开发中,短信接口被不明人士调用,注册的手机号码都无法打通,而且手机号码还不同,因短信平台对同一个手机号码做的有限制,所以公司这边需要做一个针对IP对短信进行限制。

1、先写一个自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Limiter {
    /**
     * frequency,无法超过frequency次,默认10次
     * */
    int frequency() default 10;

    /**
     * 周期时间, 默认30分钟
     * */
    int duration() default 60;

    /**
     * 返回的错误信息
     * */
    String message() default "requests are too frequent";
}

2、接下来通过AOP来对请求进行限制

@Aspect
@Component
public class LimitingAspect {
    //redis中存储的key
    private static final String LIMITER_KEY = "limit:%s:%s";
    private static final String LIMITER_BEGINTIME = "beginTime";
    private static final String LIMITER_EXFREQUENCY = "exFrequency";

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(limiter)")
    public void pointcut(Limiter limiter) {
    }

    @Around("pointcut(limiter)")
    public Object around(ProceedingJoinPoint pjp, Limiter limiter) throws Throwable {
        //获取请求的ip和访问方法的名称
        String ipAddress = WebUtil.getIpAddress();
        String methodName = pjp.getSignature().toLongString();
        //获取方法的访问周期和频率
        long cycle = limiter.duration() * 1000;
        int frequency = limiter.frequency();
        //获取访问方法的时间
        long currentTime = System.currentTimeMillis();
        //获取redis中周期内第一次访问方法的时间和执行的次数
        Object oBeginTime = redisTemplate.opsForHash().get(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_BEGINTIME);
        Long beginTime = 0L;
        if (oBeginTime != null) {
            beginTime = Long.valueOf(String.valueOf(oBeginTime));
        }
        Integer exFrequency = 0;
        Object oExFrequency = redisTemplate.opsForHash().get(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_EXFREQUENCY);
        if (oExFrequency != null) {
            exFrequency = Integer.valueOf(String.valueOf(oExFrequency));
        }

        //如果当前时间减去周期内第一次访问方法的时间大于周几时间,则正常访问
        //并将周期被第一次访问方法的时间和执行次数初始化
        if (currentTime - beginTime > cycle) {
            redisTemplate.opsForHash().put(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_BEGINTIME, String.valueOf(currentTime));
            redisTemplate.opsForHash().put(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_EXFREQUENCY, "1");
            //设置过期时间
            redisTemplate.expire(String.format(LIMITER_KEY, ipAddress, methodName), cycle, TimeUnit.MILLISECONDS);
            return pjp.proceed();
        } else {
            //如果在周期时间内,执行次数小于频率,则正常访问
            //并将执行次数加一
            if (exFrequency < frequency) {
                redisTemplate.opsForHash().increment(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_EXFREQUENCY, 1);
                return pjp.proceed();
            } else {
                //否则抛出访问频繁异常
                throw new FrequentRequestsException(limiter.message());
            }
        }
    }

}

3.获取IP的方法

public class WebUtil {

    private static final String UNKNOWN = "unknown";

    //获取request
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    //获取response
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static String getIpAddress() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        String regex = ",";
        if (ip != null && ip.indexOf(regex) > 0) {
            ip = ip.split(regex)[0];
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}

但是此方案有个弊端,当一个公司或者小区使用的是一个对外Ip时候,可能会产生问题,所以要设置合理数值

 

springmvc 中需要在配置文件中加

<aop:aspectj-autoproxy proxy-target-class="true"/>

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Spring AOP(面向切面编程)来实现接口限制访问次数的功能。 首先,需要定义一个注解来标识需要限制访问次数接口,比如@AccessLimit: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AccessLimit { int seconds(); int maxCount(); } ``` 然后,在AOP切面中实现对该注解的解析和限制访问次数的功能: ```java @Aspect @Component public class AccessLimitAspect { private final RedisTemplate<String, Integer> redisTemplate; @Autowired public AccessLimitAspect(RedisTemplate<String, Integer> redisTemplate) { this.redisTemplate = redisTemplate; } @Around("@annotation(accessLimit)") public Object around(ProceedingJoinPoint point, AccessLimit accessLimit) throws Throwable { // 获取方法名和参数作为缓存的key MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); String methodName = method.getName(); Object[] args = point.getArgs(); String key = methodName + Arrays.toString(args); // 获取当前时间戳和过期时间戳 long currentTime = System.currentTimeMillis(); long expireTime = currentTime + accessLimit.seconds() * 1000; // 查询缓存中的访问次数 Integer count = redisTemplate.opsForValue().get(key); if (count == null) { // 缓存中没有该key,表示该接口第一次被访问,设置访问次数为1并设置过期时间 redisTemplate.opsForValue().set(key, 1, accessLimit.seconds(), TimeUnit.SECONDS); } else { if (count >= accessLimit.maxCount()) { // 访问次数超过限制,返回错误信息 throw new RuntimeException("访问次数超过限制"); } else { // 访问次数加1并更新过期时间 redisTemplate.opsForValue().increment(key, 1); redisTemplate.expire(key, expireTime - currentTime, TimeUnit.MILLISECONDS); } } // 执行目标方法 return point.proceed(); } } ``` 在这个切面中,我们使用了Redis作为缓存来存储接口访问次数和过期时间。在每次访问限制接口时,我们先根据方法名和参数作为缓存的key查询缓存中的访问次数,如果缓存中没有该key,则表示该接口第一次被访问,设置访问次数为1并设置过期时间。如果缓存中已经有该key,则判断访问次数是否超过限制,如果超过限制则返回错误信息,否则访问次数加1并更新过期时间。最后执行目标方法。 要使用该AOP切面,只需要在需要限制访问次数接口上添加@AccessLimit注解即可: ```java @RestController public class UserController { @AccessLimit(seconds = 60, maxCount = 5) @GetMapping("/user/info") public String getUserInfo(@RequestParam("id") Integer id) { // ... } } ``` 这样,就可以对getUserInfo接口进行访问次数限制了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值