SpringBoot--使用redis实现分布式限流
1、引入依赖
<!-- 默认就内嵌了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>
2、在application配置文件中添加redis配置
spring:
redis:
host: *****
password:****
port: 6379
# 连接超时时间(毫秒)
timeout: 1000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
database: 0
# 连接池配置
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
3、自定义redisTemplate
由于后续要使用lua脚本来做权限控制,所以必须自定义一个redisTemplate,此处如果不自定义redisTemplate,则执行lua脚本时会报错。
package com.example.demo.utils; 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; @Configuration
public 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;
}
}
4、增加限定类型枚举类
自定义一个限定类型枚举类,后续根据类型判断,是根据ip、或是根据类型、或是根据方法名进行限流
package com.example.demo.entity;
public enum LimitType {
//自定义key
CUSTOMER,
//根据请求者IP
IP;
}
5、添加Limit注解
package com.example.demo.utils; import com.example.demo.entity.LimitType; import java.lang.annotation.*;
import java.util.concurrent.TimeUnit; @Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit { //资源名称
String name() default "";
//资源key
String key() default "";
//前缀
String prefix() default "";
//时间
int period();//最多访问次数
int count();
//类型
LimitType limintType() default LimitType.CUSTOMER;
}
6、增加Limit注解AOP实现类
增加Limit注解的AOP切面,根据注解中的类型,使用lua脚本去redis获取访问次数
package com.example.demo.utils; import com.example.demo.entity.LimitType;
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.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; @Aspect
@Configuration
public class LimitInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class); private final RedisTemplate<String, Serializable> limitRedisTemplate; public LimitInterceptor(RedisTemplate redisTemplate, RedisTemplate<String, Serializable> limitRedisTemplate) {
this.limitRedisTemplate = limitRedisTemplate;
} @Around("execution(public * *(..)) && @annotation(com.example.demo.utils.Limit)")
public Object interceptor(ProceedingJoinPoint joinPoint){
//获取连接点的方法签名对象
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取方法实例
Method method = methodSignature.getMethod();
//获取注解实例
Limit limitAnnotation = method.getAnnotation(Limit.class);
//注解中的类型
LimitType limitType = limitAnnotation.limintType();
//获取key名称
String name = limitAnnotation.name();
String key;
//获取限制时间范围
int limitPeriod = limitAnnotation.period();
//获取限制访问次数
int limitCount = limitAnnotation.count();
switch (limitType){
//如果类型是IP,则根据IP限制访问次数,key取IP地址
case IP:
key = getIPAdress();
break;
//如果类型是customer,则根据key限制访问次数
case CUSTOMER:
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 joinPoint.proceed();
}else{
throw new RuntimeException("访问超限");
}
}catch(Throwable e){
if(e instanceof RuntimeException){
throw new RuntimeException(e.getLocalizedMessage());
}
throw new RuntimeException("服务异常");
}
} /**
* lua限流脚本
* @return
*/
public String buildLuaScript(){
StringBuilder sb = new StringBuilder();
//定义c
sb.append("local c");
//获取redis中的值
sb.append("\nc = redis.call('get',KEYS[1])");
//如果调用不超过最大值
sb.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
//直接返回
sb.append("\n return c;");
//结束
sb.append("\nend");
//访问次数加一
sb.append("\nc = redis.call('incr',KEYS[1])");
//如果是第一次调用
sb.append("\nif tonumber(c) == 1 then");
//设置对应值的过期设置
sb.append("\nredis.call('expire',KEYS[1],ARGV[2])");
//结束
sb.append("\nend");
//返回
sb.append("\nreturn c;"); return sb.toString();
} private static final String UNKONW = "unknown"; /**
* 获取访问IP
* @return
*/
public String getIPAdress(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = request.getHeader("x-forword-for");
if(ip == null || ip.length() ==0 || UNKONW.equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Clent-IP");
}
if(ip == null || ip.length() ==0 || UNKONW.equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Clent-IP");
}
if(ip == null || ip.length() ==0 || UNKONW.equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
return ip;
}
}
6、增加访问控制类
在控制层添加Limit注解,返回访问次数。
@ResponseBody
@GetMapping(value = "limit")
@Limit(key = "test",period = 100, count = 5)
public String testLimit(){
return "第"+ATOMIC_INTEGER.incrementAndGet()+"次访问";
}
7、测试

当访问超过次数后,抛出异常信息(此处无权限是由于添加了shiro集成的原因)

SpringBoot--使用redis实现分布式限流的更多相关文章
- 限流(三)Redis + lua分布式限流
一.简介 1)分布式限流 如果是单实例项目,我们使用Guava这样的轻便又高性能的堆缓存来处理限流.但是当项目发展为多实例了以后呢?这时候我们就需要采用分布式限流的方式,分布式限流可以以redis + ...
- 【分布式架构】--- 基于Redis组件的特性,实现一个分布式限流
分布式---基于Redis进行接口IP限流 场景 为了防止我们的接口被人恶意访问,比如有人通过JMeter工具频繁访问我们的接口,导致接口响应变慢甚至崩溃,所以我们需要对一些特定的接口进行IP限流,即 ...
- 分布式限流组件-基于Redis的注解支持的Ratelimiter
原文:https://juejin.im/entry/5bd491c85188255ac2629bef?utm_source=coffeephp.com 在分布式领域,我们难免会遇到并发量突增,对后端 ...
- springboot + aop + Lua分布式限流的最佳实践
整理了一些Java方面的架构.面试资料(微服务.集群.分布式.中间件等),有需要的小伙伴可以关注公众号[程序员内点事],无套路自行领取 一.什么是限流?为什么要限流? 不知道大家有没有做过帝都的地铁, ...
- Redis实现的分布式锁和分布式限流
随着现在分布式越来越普遍,分布式锁也十分常用,我的上一篇文章解释了使用zookeeper实现分布式锁(传送门),本次咱们说一下如何用Redis实现分布式锁和分布限流. Redis有个事务锁,就是如下的 ...
- 从SpringBoot构建十万博文聊聊限流特技
前言 在开发十万博客系统的的过程中,前面主要分享了爬虫.缓存穿透以及文章阅读量计数等等.爬虫的目的就是解决十万+问题:缓存穿透是为了保护后端数据库查询服务:计数服务解决了接近真实阅读数以及数据库服务的 ...
- Sentinel整合Dubbo限流实战(分布式限流)
之前我们了解了 Sentinel 集成 SpringBoot实现限流,也探讨了Sentinel的限流基本原理,那么接下去我们来学习一下Sentinel整合Dubbo及 Nacos 实现动态数据源的限流 ...
- 基于kubernetes的分布式限流
做为一个数据上报系统,随着接入量越来越大,由于 API 接口无法控制调用方的行为,因此当遇到瞬时请求量激增时,会导致接口占用过多服务器资源,使得其他请求响应速度降低或是超时,更有甚者可能导致服务器宕机 ...
- Redis除了做缓存--Redis做消息队列/Redis做分布式锁/Redis做接口限流
1.用Redis实现消息队列 用命令lpush入队,rpop出队 Long size = jedis.lpush("QueueName", message);//返回存放的数据条数 ...
随机推荐
- ES6-函数与数组命名
1 箭头函数 1.1 以往js function 名字(){ 其他语句 } 1.2 现在ES6 修正了一些this,以前this可以变 ()=>{ 其他语句 } 如果只有一个参数,()可以省 . ...
- kubeadm实现k8s高可用集群环境部署与配置
高可用架构 k8s集群的高可用实际是k8s各核心组件的高可用,这里使用主备模式,架构如下: 主备模式高可用架构说明: 核心组件 高可用模式 高可用实现方式 apiserver 主备 keepalive ...
- AUTOSAR-软件规范文档阅读
https://mp.weixin.qq.com/s/Jzm9oco-MA-U7Mn_6vOzvA 基于AUTOSAR_SWS_CANDriver.pdf,Specification of CAN ...
- 【Mybatis】mybatis开启Log4j日志、增删改查操作
Mybatis日志(最常用的Log4j) 官方网站http://www.mybatis.org/mybatis-3/zh/logging.html 1.在src目录下创建一个log4j.propert ...
- Java实现 LeetCode 815 公交路线(创建关系+BFS)
815. 公交路线 我们有一系列公交路线.每一条路线 routes[i] 上都有一辆公交车在上面循环行驶.例如,有一条路线 routes[0] = [1, 5, 7],表示第一辆 (下标为0) 公交车 ...
- Java实现 蓝桥杯VIP 算法训练 与1连通的点的个数(并查集)
试题 算法训练 与1连通的点的个数 资源限制 时间限制:1.0s 内存限制:256.0MB 问题描述 没有问题描述. 输入格式 输入的第一行包含两个整数n, m n代表图中的点的个数,m代表边的个数 ...
- C# Winform退出程序的方法介绍
这篇文章主要介绍了C#中WinForm程序退出方法, 实例总结了技巧退出WinForm程序窗口的各种常用技巧,非常具有实用价值,需要的朋友可以参考下 本文实例总结了C#中WinForm程序退出方法技巧 ...
- Java实现 蓝桥杯VIP 算法提高 5-3日历
算法提高 5-3日历 时间限制:1.0s 内存限制:256.0MB 问题描述 已知2007年1月1日为星期一.设计一函数按照下述格式打印2007年以后(含)某年某月的日历,2007年以前的拒绝打印.为 ...
- Java 实现 蓝桥杯 生兔子问题
生兔子问题 有一对兔子,从出生后第四个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子.假如兔子都不死,计算第十个月兔子的总数? 分析: 四个月开始生兔子,则:F(N) = f(n-1) ...
- 第五届蓝桥杯C++B组国(决)赛真题
解题代码部分来自网友,如果有不对的地方,欢迎各位大佬评论 题目1.年龄巧合 小明和他的表弟一起去看电影,有人问他们的年龄.小明说:今年是我们的幸运年啊.我出生年份的四位数字加起来刚好是我的年龄.表弟的 ...