1、
1.首先接口限流算法:
1.计数器方式(传统计数器缺点:临界问题 可能违背定义固定速率原则)
2.令牌桶方式
3.漏桶方式
4.应用层限流(Nginx)
2.限流实现:
2.1. RateLimiter是guava提供的基于令牌桶算法的实现类,可以非常简单的完成限流特技,并且根据系统的实际情况来调整生成token的速率。
2.2.导入相关依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
2.3.代码实现不多说每一步都有注解
2.3.1 定义注解
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
double limitNum() default 20; //默认每秒放入桶中的token
}
2.3.2 封装定义返回结果
public class MyResult {
private Integer status;
private String msg;
private List<Object> data;
public MyResult(Integer status, String msg, List<Object> data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public static MyResult OK(String msg, List<Object> data) {
return new MyResult(200, msg, data);
}
public static MyResult Error(Integer status, String msg) {
return new MyResult(status, msg, null);
}
2.3.3 aop实现
@Component
@Scope
@Aspect
public class RateLimitAspect {
private Logger log = LoggerFactory.getLogger(this.getClass());
//用来存放不同接口的RateLimiter(key为接口名称,value为RateLimiter)
private ConcurrentHashMap<String, RateLimiter> map = new ConcurrentHashMap<>();
private static ObjectMapper objectMapper = new ObjectMapper();
private RateLimiter rateLimiter;
@Autowired
private HttpServletResponse response;
@Pointcut("@annotation(com.icat.retalimitaop.annotation.RateLimit)")
public void serviceLimit() {
}
@Around("serviceLimit()")
public Object around(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
Object obj = null;
//获取拦截的方法名
Signature sig = joinPoint.getSignature();
//获取拦截的方法名
MethodSignature msig = (MethodSignature) sig;
//返回被织入增加处理目标对象
Object target = joinPoint.getTarget();
//为了获取注解信息
Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
//获取注解信息
RateLimit annotation = currentMethod.getAnnotation(RateLimit.class);
double limitNum = annotation.limitNum(); //获取注解每秒加入桶中的token
String functionName = msig.getName(); // 注解所在方法名区分不同的限流策略
//获取rateLimiter
if(map.containsKey(functionName)){
rateLimiter = map.get(functionName);
}else {
map.put(functionName, RateLimiter.create(limitNum));
rateLimiter = map.get(functionName);
}
try {
if (rateLimiter.tryAcquire()) {
//执行方法
obj = joinPoint.proceed();
} else {
//拒绝了请求(服务降级)
String result = objectMapper.writeValueAsString(MyResult.Error(500, "系统繁忙!"));
log.info("拒绝了请求:" + result);
outErrorResult(result);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return obj;
}
//将结果返回
public void outErrorResult(String result) {
response.setContentType("application/json;charset=UTF-8");
try (ServletOutputStream outputStream = response.getOutputStream()) {
outputStream.write(result.getBytes("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
static {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
3.测试限流
2个接口设定没秒限流5个和美妙限流10个
@RateLimit(limitNum = 5.0)
public MyResult getResults() {
log.info("调用了方法getResults");
return MyResult.OK("调用了方法", null);
}
@RateLimit(limitNum = 10.0)
public MyResult getResultTwo() {
log.info("调用了方法getResultTwo");
return MyResult.OK("调用了方法getResultTwo", null);
}
最后的方法应该写成下面这个样子才会生效,用main方法不能生效:
@RestController
@Slf4j
public class TestLimitController {
@GetMapping(value = "/testLimit")
@RequestLimit
public R testLimit() {
log.info("开始测试限流");
return R.ok("success");
}
}
2、下面是不使用aop形式的:
三、限流工具类RateLimiter
google开源工具包guava提供了限流工具类RateLimiter,该类基于“令牌桶算法”,非常方便使用。该类的接口具体的使用请参考:RateLimiter使用实践。
RateLimiter 使用Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
四 Guava并发:ListenableFuture与RateLimiter示例
概念
ListenableFuture顾名思义就是可以监听的Future,它是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用ListenableFuture Guava帮我们检测Future是否完成了,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。
推荐使用第二种方法,因为第二种方法可以直接得到Future的返回值,或者处理错误情况。本质上第二种方法是通过调动第一种方法实现的,做了进一步的封装。
另外ListenableFuture还有其他几种内置实现:
SettableFuture:不需要实现一个方法来计算返回值,而只需要返回一个固定值来做为返回值,可以通过程序设置此Future的返回值或者异常信息
CheckedFuture: 这是一个继承自ListenableFuture接口,他提供了checkedGet()方法,此方法在Future执行发生异常时,可以抛出指定类型的异常。
RateLimiter类似于JDK的信号量Semphore,他用来限制对资源并发访问的线程数,本文介绍RateLimiter使用
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
|
Guava版本
1 2 3 4 5 |
|
3、nginx实现:
https://cloud.tencent.com/developer/article/1368499
和https://www.cnblogs.com/biglittleant/p/8979915.html
参考的文档如下:
1、 https://blog.csdn.net/qq_39816039/article/details/83988517
2、http://www.manongjc.com/article/59183.html
3、https://www.jb51.net/article/133222.htm
4、http://www.voidcn.com/article/p-wovieveo-bod.html
个人git地址:https://github.com/weidadelisq/-middleware/tree/master/spring-boot-mongodbAndRateLimter