# RateLimiter **Repository Path**: programmerry/flow-control ## Basic Information - **Project Name**: RateLimiter - **Description**: spring boot 流量控制 控制用户访问api的次数 - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 63 - **Created**: 2018-11-06 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # FlowControl(流量控制) FlowControl想要解决的问题是控制api访问次数,防止恶意调用api。支持分布式应用的使用。 spring boot 支持[flowcontrol-spring-boot-starter](https://gitee.com/shiqiyue/flow-control/tree/master/flowcontrol-spring-boot-starter) *** ### 原理 拦截链接并计数,如果超过次数,返回错误信息,没有超过次数则通过。 使用了分布式锁来控制准确的拦截。 将访问数据保存到redis来保证分布式下的运用。 分布式下运用注意要redis访问的是同一个数据库 *** ### 如何使用 * 配置流量控制信息 实现接口FlowControlConfigurer ``` public class CustomFlowControlConfigurer implements FlowControlConfigurer { /*** * 配置redis客户端 */ @Override public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer().setAddress("redis://localhost:6379"); RedissonClient redisson = Redisson.create(config); return redisson; } /*** * 配置拦截成功后-执行的动作 */ @Override public FlowControlInterceptAction flowControlInterceptAction() { return new DefaultFlowControlInterceptAction(); } /*** * 配置拦截数据来源 */ @Override public FlowControlDao flowControlDao() { return new InMemoryFlowControlDao(); } /*** * 配置redis key的命名策略 */ @Override public RedisKeyNameStrategy redisKeyNameStrategy() { return new DefaultRedisKeyNameStrategy(); } } ``` ## Filter(servlet过滤器) ``` @Configuration public class SpringMvcConfig extends WebMvcConfigurerAdapter { @Autowired private CustomFlowControlConfigurer flowControlConfigurer; /*** * 使用servlet的filter * * @return */ @Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new FlowControlFilter(flowControlConfigurer)); registration.addUrlPatterns("/*"); registration.setName("flowControlFilter"); registration.setOrder(1); return registration; } } ``` ## Interceptor(springmvc拦截器) ``` @Configuration public class SpringMvcConfig extends WebMvcConfigurerAdapter { @Autowired private CustomFlowControlConfigurer flowControlConfigurer; /*** * 使用springmvc的interceptor */ @Override public void addInterceptors(InterceptorRegistry registry) { FlowControlHandlerInterceptor flowControlHandlerInterceptor = new FlowControlHandlerInterceptor( flowControlConfigurer); registry.addInterceptor(flowControlHandlerInterceptor).addPathPatterns("/**"); super.addInterceptors(registry); } } ``` ### 样例 [flow-control-sample](https://gitee.com/shiqiyue/flow-control/tree/master/flow-control-sample) ### 采用的技术 * [redis](https://redis.io/) * [redisson](https://github.com/redisson/redisson) 分布式锁和保存访问信息 ### License Flow Control is Open Source software released under the [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0.html)