首页 > 其他分享 >Spring boot 对接口限制IP访问次数

Spring boot 对接口限制IP访问次数

时间:2022-08-27 14:11:19浏览次数:81  
标签:Spring 对接口 boot request springframework interfaceM import org annotation

1、需要的依赖

        <!-- redis依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- AOP依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- Map依赖 用redis就不需要了 -->
        <dependency>
            <groupId>net.jodah</groupId>
            <artifactId>expiringmap</artifactId>
            <version>0.5.8</version>
        </dependency>

2、定义注解

package org.springblade.modules.aspect.annotation;


import java.lang.annotation.*;

/**
 * 接口访问频率
 *
 * @author
 * @date 2022/08/27
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InterfaceAccessRestriction {

    /**
     * 时间毫秒 单位:毫秒(默认:1分钟)
     *
     * @return long
     */
    long time() default 60000;

    /**
     * 允许请求的次数 默认 5
     *
     * @return int
     */
    int value() default 30;
}

3、切面实现

借助redis实现

package org.springblade.modules.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.modules.aspect.annotation.InterfaceAccessRestriction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


/**
 * 接口访问频率
 *
 * @author
 * @date 2022/08/27
 */
@Aspect
@Component
@Slf4j
public class InterfaceAccessRestrictionAspect {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(interfaceAccessRestriction)")
    public void controllerAspect(InterfaceAccessRestriction interfaceAccessRestriction) {

    }

    @Around(value = "controllerAspect(interfaceM)", argNames = "pjp,interfaceM")
    public Object doAround(ProceedingJoinPoint pjp, InterfaceAccessRestriction interfaceM) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        BoundHashOperations<String, Object, Object> bho = redisTemplate.boundHashOps("blade:matrix:interfaceAccessRestriction" + request.getRequestURI());
        String ipCnt = (String) bho.get(request.getRemoteAddr());
        int uCount = ipCnt == null ? 0 : "".equals(ipCnt) ? 0 : Integer.parseInt(ipCnt);
        if (uCount >= interfaceM.value()) {
            log.error("接口拦截:{} 请求超过限制频率【{}次/{}ms】,IP为{}", request.getRequestURI(), interfaceM.value(), interfaceM.time(), request.getRemoteAddr());
            R<?> r = new R<>();
            r.setCode(ResultCode.FAILURE.getCode());
            r.setMsg("刷新频率过高,请" + bho.getExpire() + "秒后再操作");
            return r;
        } else {
            bho.increment(request.getRemoteAddr(), 1);
            bho.expire(interfaceM.time(), TimeUnit.MILLISECONDS);
        }
        return pjp.proceed();

    }
}

 

4、使用

 

 

5、效果

 

 

 

 

再结合自己的需求改改吧

 借鉴博客:https://www.cnblogs.com/zys2019/p/16328053.html#_label0

标签:Spring,对接口,boot,request,springframework,interfaceM,import,org,annotation
From: https://www.cnblogs.com/w-yu-chen/p/16630482.html

相关文章

  • springBoot 获取注解参数的原理
    springBoot获取注解参数的原理原理图先得到请求的request在获取可以处理请求的方法的Mapping映射器DispatcherServlet中的doDispatch方法//De......
  • 日志打印输出到控制台以及文件 Spring boot application.yml https://www.cnblogs
    转自:https://www.cnblogs.com/izyh/p/15945950.htmlyml文件中添加配置:##########日志配置-START##########logging:config:classpath:logback-spring.......
  • JPA 入门实战(3)--Spring Boot 中使用 JPA
    本文主要介绍在SpringBoot中使用JPA的方法(暂不使用spring-data-jpa),相关的环境及软件信息如下:SpringBoot2.6.10、JPA2.2、eclipselink2.7.10。1、原生使用该......
  • 78、使用Jenkins Docker 部署SpringBoot项目
    1、centOS安装Docker1、更新软件源:yumupdate2、卸载旧版本:yumremovedockerdocker-commondocker-selinuxdocker-engine3、安装软件包:yuminstall-yyum-utils......
  • SpringBoot集成thymeleaf不生效问题
    场景:在做springBoot整合Theamleaf时,用了@RestController注解,在进行试图渲染的过程中,遇到试图没有渲染成功,找到了原因,记录一下。 第一种情况:使用@RestController注解pac......
  • 一文了解SpringBoot如何开启热部署
    一文了解SpringBoot如何开启热部署本专栏将从基础开始,循序渐进,以实战为线索,逐步深入SpringBoot相关知识相关知识,打造完整的云原生学习步骤,提升工程化编码能力和思维......
  • spring中后置处理器
    Spring后置处理器(BeanPostProcessor)(BeanFactoryPostProcessor) 原创2020-12-2311:25:52 2点赞Me_Liu_Q 码龄4年关注Spring的后置处理器,在应用Spring框架开......
  • SpringBoot集成knife4j
    <dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>2.0.3</version></dependency>......
  • springboot 使用 JSR303 校验
    JSR303用于后端校验前端传来的数据如何使用引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation<......
  • SpringCould-概要
    1.什么是微服务?在知道什么是微服务之前,我们还得知道什么是单体架构和分布式架构单体架构:           将业务的所有功能集中在一个项目中开发,打成一个包......