Springboot+Redis实现API接口限流的示例代码

 更新时间:2021年07月28日 08:46:35   作者:· Coisini  
本文主要介绍了Springboot+Redis实现API接口限流的示例代码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

添加Redis的jar包.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

在application.yml中配置redis

spring:
  ## Redis
    redis:
      database: 0
      host: 127.0.0.1
      port: 6379
      password:
      jedis:
        pool:
          max-active: 8
          max-wait: -1ms
          max-idle: 8
          min-idle: 0
      timeout: 2000ms

添加自定义注解

@Inherited
@Documented
@Target({ElementType.FIELD,ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessLimit {

    //指定second 时间内 API请求次数
    int times() default 4;

    // 请求次数的指定时间范围  秒数(redis数据过期时间)
    int second() default 10;
}

编写拦截器

import com.ys.xlb.annotation.AccessLimit;
import com.ys.xlb.bean.Code;
import com.ys.xlb.exception.GlobalException;
import com.ys.xlb.utils.IpUtils;
import com.ys.xlb.utils.RequestUtils;
import com.ys.xlb.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AccessLimitInterceptor
 * @description: API请求限流拦截器
 * @time 2019-04-20 11:08
 **/
@Slf4j
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            // Handler 是否为 HandlerMethod 实例
            if(handler instanceof HandlerMethod){
                // 强转
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 获取方法
                Method method = handlerMethod.getMethod();
                // 是否有AccessLimit注解
                if(!method.isAnnotationPresent(AccessLimit.class)){
                    return true;
                }
                // 获取注解内容信息
                AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);
                if(accessLimit == null){
                    return true;
                }
                int times = accessLimit.times();//请求次数
                int second = accessLimit.second();//请求时间范围
                //根据 IP + API 限流
                String key = IpUtils.getIpAddr(request) + request.getRequestURI();
                //根据key获取已请求次数
                Integer maxTimes = redisTemplate.opsForValue().get(key);
                if(maxTimes == null){
                    //set时一定要加过期时间
                    redisTemplate.opsForValue().set(key, 1, second, TimeUnit.SECONDS);
                }else if(maxTimes < times){
                    redisTemplate.opsForValue().set(key, maxTimes+1, second, TimeUnit.SECONDS);
                }else{
                    // 30405 API_REQUEST_TOO_MUCH  请求过于频繁
                    RequestUtils.out(response, ResultUtils.error(Code.API_REQUEST_TOO_MUCH));
                    return false;
                }
            }
        }catch (Exception e){
            log.error("API请求限流拦截异常,请检查Redis是否开启!",e);
            throw new GlobalException(Code.BAD_REQUEST,e.getMessage());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

方法中的IP工具类方法

 /**
     * IpUtils工具类方法
     * 获取真实的ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(org.apache.commons.lang.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(org.apache.commons.lang.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }

RequestUtils.out()方法

 /**
     * @Title: out
     * @Description:  response输出JSON数据
     * @param response : 响应请求
     * @param object: object
     * @return void
     **/
    public static void out(ServletResponse response, Object object){
        PrintWriter out = null;
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.println(JSONObject.fromObject(resultMap).toString());
        } catch (Exception e) {
            log.error("输出JSON报错!"+e);
        }finally{
            if(null != out){
                out.flush();
                out.close();
            }
        }
    }

配置拦截器

@Configuration
public class ApplicationConfig implements WebMvcConfigurer {

 //这里需要注入拦截器 否则无法获取到拦截器注入的RedisTemplate<String, Integer> redisTemplate; 
 @Bean
    public AccessLimitInterceptor accessLimitInterceptor(){
        return new AccessLimitInterceptor();
    }

 /**
     * 配置拦截器
     * @author lance
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**","/login.html","/user/login");
        //API限流拦截
        registry.addInterceptor(accessLimitInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**","/login.html");
    }
}

配置拦截器的类中必须先注入这个拦截器否则无法获取到拦截器注入的RedisTemplate<String, Integer> redisTemplate

使用注解

/**
     * @Title: selectAll
     * @Description: 查询文章信息
     **/
    @AccessLimit(times = 5)
    @RequestMapping(value = "selectAll" , method = {RequestMethod.GET,RequestMethod.POST})
    //GetMapping(value = "selectAll")
    public ResultBody selectAll(Article article) {
        return articleService.selectAll(article);
    }

请求测试

时间间隔为默认的10s, 10s内请求第6次出现此返回值,完成.

参考博客:
https://blog.csdn.net/zrg523/article/details/82185088

到此这篇关于Springboot+Redis实现API接口限流的示例代码的文章就介绍到这了,更多相关Springboot+Redis接口API限流内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Lombok 安装和使用小技巧

    Lombok 安装和使用小技巧

    这篇文章主要介绍了Lombok 安装和使用指南,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • Mybatis-plus批量去重插入ON DUPLICATE key update使用方式

    Mybatis-plus批量去重插入ON DUPLICATE key update使用方式

    这篇文章主要介绍了Mybatis-plus批量去重插入ON DUPLICATE key update使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • spring MVC中传递对象参数示例详解

    spring MVC中传递对象参数示例详解

    这篇文章主要给大家介绍了在spring MVC中传递对象参数的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看吧。
    2017-06-06
  • Maven打包SpringBoot工程的实现示例

    Maven打包SpringBoot工程的实现示例

    在使用Spring Boot和Maven的项目中,你可以使用Maven来打包你的项目,本文主要介绍了Maven打包SpringBoot工程的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2024-05-05
  • Spring Cloud Alibaba负载均衡实现方式

    Spring Cloud Alibaba负载均衡实现方式

    这篇文章主要为大家介绍了Spring Cloud Alibaba负载均衡实现方式详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • Java异常链表throw结构assert详细解读

    Java异常链表throw结构assert详细解读

    这篇文章主要给大家介绍了关于Java中方法使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • 有关Java中的BeanInfo介绍

    有关Java中的BeanInfo介绍

    Java的BeanInfo在工作中并不怎么用到,我也是在学习spring源码的时候,发现SpringBoot启动时候会设置一个属叫"spring.beaninfo.ignore",网上一些地方说这个配置的意思是是否跳过java BeanInfo的搜索,但是BeanInfo又是什么呢?本文我们将对此做一个详细介绍
    2021-09-09
  • java正则表达式的简单运用

    java正则表达式的简单运用

    这篇文章主要为大家详细介绍了java正则表达式的简单运用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08
  • springboot整合rocketmq实现分布式事务

    springboot整合rocketmq实现分布式事务

    大多数情况下很多公司是使用消息队列的方式实现分布式事务。 本篇文章重点讲解springboot环境下整合rocketmq实现分布式事务,感兴趣的可以了解一下
    2021-05-05
  • Java设计模式常用原则解析

    Java设计模式常用原则解析

    这篇文章主要介绍了Java设计模式常用原则解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05

最新评论