自定义限流注解@RateLimiter

简介: 自定义限流注解@RateLimiter

定义注解

/**
 * 限流注解
 * 
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter
{
    /**
     * 限流key
     */
    public String key() default CacheConstants.RATE_LIMIT_KEY;
    /**
     * 限流时间,单位秒
     */
    public int time() default 60;
    /**
     * 限流次数
     */
    public int count() default 100;
    /**
     * 限流类型
     */
    public LimitType limitType() default LimitType.DEFAULT;
}

对应注解限流处理切面

/**
 * 限流处理
 *
 */
@Aspect
@Component
public class RateLimiterAspect
{
    private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);
    private RedisTemplate<Object, Object> redisTemplate;
    private RedisScript<Long> limitScript;
    @Autowired
    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate)
    {
        this.redisTemplate = redisTemplate;
    }
    @Autowired
    public void setLimitScript(RedisScript<Long> limitScript)
    {
        this.limitScript = limitScript;
    }
    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable
    {
        String key = rateLimiter.key();
        int time = rateLimiter.time();
        int count = rateLimiter.count();
        String combineKey = getCombineKey(rateLimiter, point);
        List<Object> keys = Collections.singletonList(combineKey);
        try
        {
            Long number = redisTemplate.execute(limitScript, keys, count, time);
            if (StringUtils.isNull(number) || number.intValue() > count)
            {
                throw new RuntimeException("访问过于频繁,请稍候再试");
            }
            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);
        }
        catch (RuntimeException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new RuntimeException("服务器限流异常,请稍候再试");
        }
    }
    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
    {
        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP)
        {
            stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }
}

LimitType

/**
 * 限流类型
 *
 */
public enum LimitType
{
    /**
     * 默认策略全局限流
     */
    DEFAULT,
    /**
     * 根据请求者IP进行限流
     */
    IP
}

Redis使用FastJson序列化

/**
 * Redis使用FastJson序列化
 * 
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class<T> clazz;
    public FastJson2JsonRedisSerializer(Class<T> clazz)
    {
        super();
        this.clazz = clazz;
    }
    @Override
    public byte[] serialize(T t) throws SerializationException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }
    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
    }
}

RedisConfig

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }
    @Bean
    public DefaultRedisScript<Long> limitScript()
    {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(limitScriptText());
        redisScript.setResultType(Long.class);
        return redisScript;
    }
    /**
     * 限流脚本
     */
    private String limitScriptText()
    {
        return "local key = KEYS[1]\n" +
                "local count = tonumber(ARGV[1])\n" +
                "local time = tonumber(ARGV[2])\n" +
                "local current = redis.call('get', key);\n" +
                "if current and tonumber(current) > count then\n" +
                "    return tonumber(current);\n" +
                "end\n" +
                "current = redis.call('incr', key)\n" +
                "if tonumber(current) == 1 then\n" +
                "    redis.call('expire', key, time)\n" +
                "end\n" +
                "return tonumber(current);";
    }
}

使用@RateLimiter限流

@ApiOperation(value = "查询列表",tags = "学员")
    @PostMapping(value = "/list")
    @RateLimiter(time = 10, count = 10, limitType = LimitType.IP)  //同一个IP,10秒内最多访问10次
    public CommonResult studentList(@RequestBody StudentInfo params){
        PageInfo<StudentInfo> pageList = studentInfoService.getStudentInfoPages(params);
        DicTransferUtils.transfer(pageList);//字典翻译
        return ResultUtil.page(pageList.getList(),(int) pageList.getTotal());
    }
目录
相关文章
|
存储 NoSQL 搜索推荐
若依框架----源码分析(@RateLimiter)
若依框架----源码分析(@RateLimiter)
1252 0
|
算法 网络协议 Java
Spring Boot 的接口限流算法
本文介绍了高并发系统中流量控制的重要性及常见的限流算法。首先讲解了简单的计数器法,其通过设置时间窗口内的请求数限制来控制流量,但存在临界问题。接着介绍了滑动窗口算法,通过将时间窗口划分为多个格子,提高了统计精度并缓解了临界问题。随后详细描述了漏桶算法和令牌桶算法,前者以固定速率处理请求,后者允许一定程度的流量突发,更符合实际需求。最后对比了各算法的特点与适用场景,指出选择合适的算法需根据具体情况进行分析。
1068 56
Spring Boot 的接口限流算法
|
8月前
|
关系型数据库 MySQL Java
SpringCloud工程部署启动
本教程介绍SpringCloud微服务项目搭建与部署,支持完整工程导入或从零构建。涵盖父工程、子模块创建,POM依赖管理,user-service与order-service模块开发,数据库配置及业务代码编写。通过RestTemplate实现服务间远程调用,解决跨服务数据获取问题,帮助理解微服务拆分与通信机制,为后续深入学习打下基础。
|
前端开发
PDF文件上传转成base64编码并支持预览
PDF文件上传转成base64编码并支持预览
1433 12
|
分布式计算 运维 监控
Fusion 引擎赋能:流利说如何用阿里云 Serverless Spark 实现数仓计算加速
本文介绍了流利说与阿里云合作,利用EMR Serverless Spark优化数据处理的全过程。流利说是科技驱动的教育公司,通过AI技术提升用户英语水平。原有架构存在资源管理、成本和性能等痛点,采用EMR Serverless Spark后,实现弹性资源管理、按需计费及性能优化。方案涵盖数据采集、存储、计算到查询的完整能力,支持多种接入方式与高效调度。迁移后任务耗时减少40%,失败率降低80%,成本下降30%。未来将深化合作,探索更多行业解决方案。
1000 1
|
NoSQL IDE MongoDB
Studio 3T 2025.5 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
Studio 3T 2025.5 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
588 2
Studio 3T 2025.5 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
|
Linux 数据安全/隐私保护 Windows
解决Windows密码丢失问题:详细指南
最近因为某些工作缘故,接触到windows比较频繁,特此记录一下 当下,计算机安全是每个人都不能忽视的重要问题。然而,有时可能因为忘记密码而无法访问自己的Windows系统,这会导致数据和信息的临时不可用。 本文将详细介绍两种场景下的密码恢复方法:一种是针对虚拟机,另一种适用于物理机。通过这些方法,可以快速恢复对系统的访问,确保业务的连续性。
解决Windows密码丢失问题:详细指南
|
消息中间件 Java 测试技术
技术分享:探讨@Transactional与@Async的共舞——能否同时使用及最佳实践
【8月更文挑战第13天】在Java的Spring框架中,@Transactional和@Async是两个非常强大的注解,它们分别用于控制事务的边界和优化应用程序的性能通过异步执行。然而,当这两个注解碰撞在一起时,是否能够和谐共存,成为了很多开发者在设计和构建高性能、高可靠性的应用程序时面临的一个关键问题。本文将深入探讨@Transactional与@Async的联合使用场景、潜在问题以及最佳实践。
1230 0