优雅解决分布式限流

SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程

在前面的两篇文章中,介绍了一些限流的类型和策略,本篇从 Spring BootRedis 应用层面来实现分布式的限流….

分布式限流

单机版中我们了解到 AtomicIntegerRateLimiterSemaphore 这几种解决方案,但它们也仅仅是单机的解决手段,在集群环境下就透心凉了,后面又讲述了 Nginx 的限流手段,可它又属于网关层面的策略之一,并不能解决所有问题。例如供短信接口,你无法保证消费方是否会做好限流控制,所以自己在应用层实现限流还是很有必要的。

本章目标

利用 自定义注解Spring AopRedis Cache 实现分布式限流….

具体代码

很简单…

导入依赖

在 pom.xml 中添加上 starter-webstarter-aopstarter-data-redis 的依赖即可,习惯了使用 commons-lang3 和 guava 中的一些工具包…

12345678910111213141516171819202122232425262728
<dependencies>    <!-- 默认就内嵌了Tomcat 容器,如需要更换容器也极其简单-->    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-aop</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-data-redis</artifactId>    </dependency>    <dependency>        <groupId>com.google.guava</groupId>        <artifactId>guava</artifactId>        <version>21.0</version>    </dependency>    <dependency>        <groupId>org.apache.commons</groupId>        <artifactId>commons-lang3</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-test</artifactId>    </dependency></dependencies>

属性配置

在 application.properites 资源文件中添加 redis 相关的配置项

123
spring.redis.host=localhostspring.redis.port=6379spring.redis.password=battcn

Limit 注解

创建一个 Limit 注解,不多说注释都给各位写齐全了….

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
package com.battcn.limiter.annotation;

import com.battcn.limiter.LimitType;

import java.lang.annotation.*;

/** * 限流 * * @author Levin * @since 2018-02-05 */@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Limit {

    /**     * 资源的名字     *     * @return String     */    String name() default "";

    /**     * 资源的key     *     * @return String     */    String key() default "";

    /**     * Key的prefix     *     * @return String     */    String prefix() default "";

    /**     * 给定的时间段     * 单位秒     *     * @return int     */    int period();

    /**     * 最多的访问限制次数     *     * @return int     */    int count();

    /**     * 类型     *     * @return LimitType     */    LimitType limitType() default LimitType.CUSTOMER;}

public enum LimitType {    /**     * 自定义key     */    CUSTOMER,    /**     * 根据请求者IP     */    IP;}

RedisTemplate

默认情况下 spring-boot-data-redis 为我们提供了StringRedisTemplate 但是满足不了其它类型的转换,所以还是得自己去定义其它类型的模板….

123456789101112131415161718192021222324252627
package com.battcn.limiter;

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/** * @author Levin * @since 2018/8/2 0002 */@Configurationpublic class RedisLimiterHelper {

    @Bean    public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {        RedisTemplate<String, Serializable> template = new RedisTemplate<>();        template.setKeySerializer(new StringRedisSerializer());        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());        template.setConnectionFactory(redisConnectionFactory);        return template;    }}

Limit 拦截器(AOP)

熟悉 Redis 的朋友都知道它是线程安全的,我们利用它的特性可以实现分布式锁、分布式限流等组件,在一起来学SpringBoot | 第二十三篇:轻松搞定重复提交(分布式锁)中讲述了分布式锁的实现,限流相比它稍微复杂一点,官方虽然没有提供相应的API,但却提供了支持 Lua 脚本的功能,我们可以通过编写 Lua 脚本实现自己的API,同时他是满足原子性的….

下面核心就是调用 execute 方法传入我们的 Lua 脚本内容,然后通过返回值判断是否超出我们预期的范围,超出则给出错误提示。

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
package com.battcn.limiter;

import com.battcn.limiter.annotation.Limit;import com.google.common.collect.ImmutableList;import org.apache.commons.lang3.StringUtils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.script.DefaultRedisScript;import org.springframework.data.redis.core.script.RedisScript;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;import java.io.Serializable;import java.lang.reflect.Method;

/** * @author Levin * @since 2018/2/5 0005 */@Aspect@Configurationpublic class LimitInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);

    private final RedisTemplate<String, Serializable> limitRedisTemplate;

    @Autowired    public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) {        this.limitRedisTemplate = limitRedisTemplate;    }

    @Around("execution(public * *(..)) && @annotation(com.battcn.limiter.annotation.Limit)")    public Object interceptor(ProceedingJoinPoint pjp) {        MethodSignature signature = (MethodSignature) pjp.getSignature();        Method method = signature.getMethod();        Limit limitAnnotation = method.getAnnotation(Limit.class);        LimitType limitType = limitAnnotation.limitType();        String name = limitAnnotation.name();        String key;        int limitPeriod = limitAnnotation.period();        int limitCount = limitAnnotation.count();        switch (limitType) {            case IP:                key = getIpAddress();                break;            case CUSTOMER:                // TODO 如果此处想根据表达式或者一些规则生成 请看 一起来学Spring Boot | 第二十三篇:轻松搞定重复提交(分布式锁)                key = limitAnnotation.key();                break;            default:                key = StringUtils.upperCase(method.getName());        }        ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));        try {            String luaScript = buildLuaScript();            RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);            Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);            logger.info("Access try count is {} for name={} and key = {}", count, name, key);            if (count != null && count.intValue() <= limitCount) {                return pjp.proceed();            } else {                throw new RuntimeException("You have been dragged into the blacklist");            }        } catch (Throwable e) {            if (e instanceof RuntimeException) {                throw new RuntimeException(e.getLocalizedMessage());            }            throw new RuntimeException("server exception");        }    }

    /**     * 限流 脚本     *     * @return lua脚本     */    public String buildLuaScript() {        StringBuilder lua = new StringBuilder();        lua.append("local c");        lua.append("\nc = redis.call(‘get‘,KEYS[1])");        // 调用不超过最大值,则直接返回        lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");        lua.append("\nreturn c;");        lua.append("\nend");        // 执行计算器自加        lua.append("\nc = redis.call(‘incr‘,KEYS[1])");        lua.append("\nif tonumber(c) == 1 then");        // 从第一次调用开始限流,设置对应键值的过期        lua.append("\nredis.call(‘expire‘,KEYS[1],ARGV[2])");        lua.append("\nend");        lua.append("\nreturn c;");        return lua.toString();    }

    private static final String UNKNOWN = "unknown";

    public String getIpAddress() {        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).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();        }        return ip;    }}

控制层

在接口上添加 @Limit() 注解,如下代码会在 Redis 中生成过期时间为 100s 的 key = test 的记录,特意定义了一个 AtomicInteger 用作测试…

123456789101112131415161718192021222324
package com.battcn.controller;

import com.battcn.limiter.annotation.Limit;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/** * @author Levin * @since 2018/8/2 0002 */@RestControllerpublic class LimiterController {

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

    @Limit(key = "test", period = 100, count = 10)    @GetMapping("/test")    public int testLimiter() {        // 意味著 100S 内最多允許訪問10次        return ATOMIC_INTEGER.incrementAndGet();    }}

主函数

就一个普通的不能在普通的主函数类了

123456789101112131415
package com.battcn;

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;

/** * @author Levin */@SpringBootApplicationpublic class Chapter27Application {

    public static void main(String[] args) {        SpringApplication.run(Chapter27Application.class, args);    }}

测试

完成准备事项后,启动 Chapter27Application 自行测试即可,测试手段相信大伙都不陌生了,如 浏览器postmanjunitswagger,此处基于 postman,如果你觉得自带的异常信息不够友好,那么配上一起来学SpringBoot | 第十八篇:轻松搞定全局异常 可以轻松搞定…

未达设定的阀值时

正确响应

达到设置的阀值时

错误响应

原文地址:https://www.cnblogs.com/lywJ/p/10715367.html

时间: 2024-07-31 08:11:21

优雅解决分布式限流的相关文章

巧用SpringBoot优雅解决分布式限流

SpringBoot?是为了简化?Spring?应用的创建.运行.调试.部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程 本篇从?Spring Boot.Redis?应用层面来实现分布式的限流-. 分布式限流 单机版中我们了解到 AtomicInteger.RateLimiter.Semaphore 这几种解决方案,但它们也仅仅是单机的解决手段,在集群环境下就透心凉了,后面又讲述了

微服务架构下的分布式限流方案思考

1.微服务限流 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.缓存.降级和限流是保护微服务系统运行稳定性的三大利器.缓存的目的是提升系统访问速度和增大系统能处理的容量,而降级是当服务出问题或者影响到核心流程的性能则需要暂时屏蔽掉,待高峰或者问题解决后再打开,而有些场景并不能用缓存和降级来解决,比如稀缺资源.数据库的写操作.频繁的复杂查询,因此需有一种手段来限制这些场景的请求量,即限流. 比如当我们设计了一个函数,准备上线,这时候这个函数会消耗一些资源,处理上限是1秒服务3000个QPS

程序员修神之路--高并发优雅的做限流(有福利)

菜菜哥,有时间吗? YY妹,什么事? 我最近的任务是做个小的秒杀活动,我怕把后端接口压垮,X总说这可关系到公司的存亡 简单呀,你就做个限流呗 这个没做过呀,菜菜哥,帮妹子写一个呗,事成了,以后有什么要求随便说 那好呀,先把我工资涨一下 那算了,我找别人帮忙吧 跟你开玩笑呢,给哥2个小时时间 谢谢菜菜哥,以后你什么要求我都答应你 好嘞,年轻人就是豪爽 ◆◆ 技术分析 ◆◆ 如果你比较关注现在的技术形式,就会知道微服务现在火的一塌糊涂,当然,事物都有两面性,微服务也不是解决技术,架构等问题的万能钥匙

【分布式架构】(10)---基于Redis组件的特性,实现一个分布式限流

分布式---基于Redis进行接口IP限流 场景 为了防止我们的接口被人恶意访问,比如有人通过JMeter工具频繁访问我们的接口,导致接口响应变慢甚至崩溃,所以我们需要对一些特定的接口进行IP限流,即一定时间内同一IP访问的次数是有限的. 实现原理 用Redis作为限流组件的核心的原理,将用户的IP地址当Key,一段时间内访问次数为value,同时设置该Key过期时间. 比如某接口设置相同IP10秒内请求5次,超过5次不让访问该接口. 1. 第一次该IP地址存入redis的时候,key值为IP地

用nginx实现分布式限流(防DDOS攻击)

1.前言 一般对外暴露的系统,在促销或者黑客攻击时会涌来大量的请求,为了保护系统不被瞬间到来的高并发流量给打垮, 就需要限流 . 本文主要阐述如何用nginx 来实现限流. 听说 Hystrix 也可以, 各位有兴趣可以去研究哈 . 2. 首先部署一个对外暴露接口的程序 我这里部署的是一个spring boot 项目 里面暴露了如下接口, 很简单 package com.anuo.app.controller; import org.slf4j.Logger; import org.slf4j.

springboot + aop + Lua分布式限流原理解析

一.什么是限流?为什么要限流?不知道大家有没有做过帝都的地铁,就是进地铁站都要排队的那种,为什么要这样摆长龙转圈圈?答案就是为了 限流 !因为一趟地铁的运力是有限的,一下挤进去太多人会造成站台的拥挤.列车的超载,存在一定的安全隐患.同理,我们的程序也是一样,它处理请求的能力也是有限的,一旦请求多到超出它的处理极限就会崩溃.为了不出现最坏的崩溃情况,只能耽误一下大家进站的时间. 限流是保证系统高可用的重要手段!!! 由于互联网公司的流量巨大,系统上线会做一个流量峰值的评估,尤其是像各种秒杀促销活动

从构建分布式秒杀系统聊聊限流的多种实现

前言 俗话说的好,冰冻三尺非一日之寒,滴水穿石非一日之功,罗马也不是一天就建成的.两周前秒杀案例初步成型,分享到了中国最大的同×××友网站-码云.同时也收到了不少小伙伴的建议和投诉.我从不认为分布式.集群.秒杀这些就应该是大厂的专利,在互联网的今天无论什么时候都要时刻武装自己,只有这样,也许你的春天就在明天. 在开发秒杀系统案例的过程中,前面主要分享了队列.缓存.锁和分布式锁以及静态化等等.缓存的目的是为了提升系统访问速度和增强系统的处理能力:分布式锁解决了集群下数据的安全一致性问题:静态化无疑

从构建分布式秒杀系统聊聊限流特技

前言 俗话说的好,冰冻三尺非一日之寒,滴水穿石非一日之功,罗马也不是一天就建成的.两周前秒杀案例初步成型,分享到了中国最大的同性交友网站-码云.同时也收到了不少小伙伴的建议和投诉.我从不认为分布式.集群.秒杀这些就应该是大厂的专利,在互联网的今天无论什么时候都要时刻武装自己,只有这样,也许你的春天就在明天. 在开发秒杀系统案例的过程中,前面主要分享了队列.缓存.锁和分布式锁以及静态化等等.缓存的目的是为了提升系统访问速度和增强系统的处理能力:分布式锁解决了集群下数据的安全一致性问题:静态化无疑是

高并发限流策略

在开发高并发系统时有三把利器用来保护系统:缓存.降级和限流.缓存的目的是提升系统访问速度和增大系统能处理的容量,可谓是抗高并发流量的银弹:而降级是当服务出问题或者影响到核心流程的性能则需要暂时屏蔽掉,待高峰或者问题解决后再打开:而有些场景并不能用缓存和降级来解决,比如稀缺资源(秒杀.抢购).写服务(如评论.下单).频繁的复杂查询(评论的最后几页),因此需有一种手段来限制这些场景的并发/请求量,即限流. 限流的目的是通过对并发访问/请求进行限速或者一个时间窗口内的的请求进行限速来保护系统,一旦达到