当前位置: 首页 > news >正文

java Redisson 实现限流每秒/分钟/小时限制N个

1.引入maven包:

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

2.代码实现:

a.RedissonConfig 初始化

package com.hanyc.demo.config;import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.ArrayList;
import java.util.List;/*** redisson** @author hanyc* @date 2024/12/31 13:30* @company: */
@Configuration
public class RedissonConfig {@Autowiredprivate RedisProperties redisProperties;@Beanpublic RedissonClient redissonClient() {Config config = new Config();if (redisProperties.getCluster() != null && !redisProperties.getCluster().getNodes().isEmpty()) {RedisProperties.Cluster cluster = redisProperties.getCluster();List<String> nodes = cluster.getNodes();List<String> newNodes = new ArrayList<>();nodes.forEach(index -> newNodes.add(index.startsWith("redis://") ? index : "redis://" + index));config.useClusterServers().addNodeAddress(newNodes.toArray(new String[0])).setPassword(redisProperties.getPassword());} else {String address = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();config.useSingleServer().setAddress(address).setPassword(redisProperties.getPassword());}RedissonClient redisson = Redisson.create(config);return redisson;}
}

b.UserRateLimiterInterceptor  用户请求限流拦截器

package com.hanyc.demo.config;import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** @Description: 用户请求限流拦截器* @Author hanyc* @Date 2024/12/12**/
@Component
@Slf4j
public class UserRateLimiterInterceptor implements HandlerInterceptor {@Autowiredprivate RedissonClient redissonClient;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 假设这个方法能够从请求中解析出用户IDString userIdStr = "";String userIp = ServletUtil.getClientIP(request);// 假设用户ID 为 1String userId = "1";if (userId == null) {// 所有未登录账号 不需要验证的请求,都使用userId=10000userIdStr = userIp;} else {userIdStr = userId.toString();}// 为每个用户生成唯一的限流键String rateLimiterKey = "USER_RATE_LIMITER" + userIdStr;// 删除 Redis 中存储的限流器状态(清除缓存)// RRateLimiter 在内部将配置保存在 Redis 中,并且这些配置是持久化的。删除该键后,Redis 会丢失之前存储的限流配置,从而确保新的配置能够被应用。redissonClient.getBucket(rateLimiterKey).delete();// 获取分布式的 RRateLimiter 实例RRateLimiter rateLimiter = redissonClient.getRateLimiter(rateLimiterKey);// 初始化限流器,限制每两秒最多 10 次请求// 参数说明: // RateType.OVERALL 全局// rate 时间限制内可以请求多少次// rateInterval 多少时间内限制// 时间单位 可以秒/分钟/小时等rateLimiter.trySetRate(RateType.OVERALL, 10, 2, RateIntervalUnit.SECONDS);log.info("当前路由为:{} userIdStr:{} userIp:{}", request.getRequestURI(), userIdStr, userIp);// 尝试获取令牌,如果获取不到说明超过请求限制if (rateLimiter.tryAcquire()) {// 允许继续处理请求return true;} else {// 如果获取不到令牌,则说明请求超过了限制,可以在这里抛出异常或者返回错误信息log.warn("当前异常的路由为:{} userIdStr:{} userIp :{}", request.getRequestURI(), userIdStr, userIp);return false;}}}

c. WebMvcConfig 添加自定义拦截器

package com.hanyc.demo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** MVC自定义配置** @author hanyc*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Beanpublic UserRateLimiterInterceptor userRateLimiterInterceptor() {return new UserRateLimiterInterceptor();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(userRateLimiterInterceptor()).addPathPatterns("/**");}
}

3.测试

使用JMeter 发送请求. 每秒15个.

查看打印结果:

前10个请求正常响应. 后五个请求被拦截


http://www.mrgr.cn/news/82204.html

相关文章:

  • sudoers文件修改格式错误恢复
  • Linux 小火车
  • 二、vue智能Ai对话(高仿通义千问)流式进阶版
  • 赢涛智慧工单源码独立版+搭建环境教程
  • 记录一次Android Studio的下载、安装、配置
  • 前端开发:Web前端和HTML
  • 【复刻】ESG表现对企业价值的影响机制研究(2009-2021年)
  • 一、VxLAN 简介
  • 旷视科技Java面试题及参考答案
  • NRF24L01模块通信实验
  • 日期时间选择(设置禁用状态)
  • linux系统安装搭建chrony(ntp)时间同步服务器
  • git使用指南-实践-搭建git私服
  • 数据仓库中的指标体系模型介绍
  • Frontend - 分页(针对 python / Django )
  • 用Python操作字节流中的Excel工作簿
  • SpringCloud源码分析-Ribbon与LoadBalancer
  • python实现自动登录12306抢票 -- selenium
  • Yolo11改进策略:注意力改进|Neck层改进|SCSA,探索空间与通道注意力之间的协同效应|即插即用
  • 【Rust自学】9.2. Result枚举与可恢复的错误 Pt.1:match、expect和unwrap处理错误
  • 【Rust自学】9.1. 不可恢复的错误以及panic!
  • 【Rust自学】8.6. HashMap Pt.2:更新HashMap
  • 深入探讨服务器虚拟化:架构、技术与应用
  • 我们能否使用 ANSYS SPEOS 测量水质?
  • Unity3D仿星露谷物语开发14之Custom Property Attribute
  • 偏移类窗口函数—— LAG()、LEAD()用法详解