推荐大家关注一个公众号

后台回复“大礼包”有惊喜礼包!

日英文

We all have a past. It’s how you deal with it.

每个人都有过去,只是取决于你怎么去处理。

每日掏心话

伪装了多久,终于将自己的心变成石头,可突然想起你时,疼的感觉依然那么熟悉!

责编:乐乐 | 来自:饭一碗 链接:blog.csdn.net/fanrenxiang/article/details/80949079

往日回顾:

正文

大家好,我是小乐。

Guava提供的RateLimiter可以限制物理或逻辑资源的被访问速率,咋一听有点像java并发包下的Samephore,但是又不相同,RateLimiter控制的是速率,Samephore控制的是并发量。

RateLimiter的原理类似于令牌桶,它主要由许可发出的速率来定义,如果没有额外的配置,许可证将按每秒许可证规定的固定速度分配,许可将被平滑地分发,若请求超过permitsPerSecond则RateLimiter按照每秒 1/permitsPerSecond 的速率释放许可。


com.google.guava
guava
23.0

public static void main(String[] args) {
String start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
RateLimiter limiter = RateLimiter.create(1.0); // 这里的1表示每秒允许处理的量为1个
for (int i = 1; i <= 10; i++) {
limiter.acquire();// 请求RateLimiter, 超过permits会被阻塞
System.out.println("call execute.." + i);
}
String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println("start time:" + start);
System.out.println("end time:" + end);
}

打开网易新闻 查看更多图片
图片

可以看到,我假定了每秒处理请求的速率为1个,现在我有10个任务要处理,那么RateLimiter就很好的实现了控制速率,总共10个任务,需要9次获取许可,所以最后10个任务的消耗时间为9s左右。那么在实际的项目中是如何使用的呢??

实际项目中使用@Service
public class GuavaRateLimiterService {
/*每秒控制5个许可*/
RateLimiter rateLimiter = RateLimiter.create(5.0);

/**
* 获取令牌
*
* @return
*/
public boolean tryAcquire() {
return rateLimiter.tryAcquire();
}

}
@Autowired
private GuavaRateLimiterService rateLimiterService;

@ResponseBody
@RequestMapping("/ratelimiter")
public Result testRateLimiter(){
if(rateLimiterService.tryAcquire()){
return ResultUtil.success1(1001,"成功获取许可");
}
return ResultUtil.success1(1002,"未获取到许可");
}

jmeter起10个线程并发访问接口,测试结果如下:


图片

可以发现,10个并发访问总是只有6个能获取到许可,结论就是能获取到RateLimiter.create(n)中n+1个许可,总体来看Guava的RateLimiter是比较优雅的。本文就是简单的提了下RateLimiter的使用。

翻阅发现使用上述方式使用RateLimiter的方式不够优雅,尽管我们可以把RateLimiter的逻辑包在service里面,controller直接调用即可,但是如果我们换成:自定义注解+切面 的方式实现的话,会优雅的多,详细见下面代码:

自定义注解类

import java.lang.annotation.*;

/**
* 自定义注解可以不包含属性,成为一个标识注解
*/
@Inherited
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimitAspect {

}

自定义切面类

import com.google.common.util.concurrent.RateLimiter;
import com.simons.cn.springbootdemo.util.ResultUtil;
import net.sf.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Scope
@Aspect
public class RateLimitAop {

@Autowired
private HttpServletResponse response;

private RateLimiter rateLimiter = RateLimiter.create(5.0); //比如说,我这里设置"并发数"为5

@Pointcut("@annotation(com.simons.cn.springbootdemo.aspect.RateLimitAspect)")
public void serviceLimit() {

@Around("serviceLimit()")
public Object around(ProceedingJoinPoint joinPoint) {
Boolean flag = rateLimiter.tryAcquire();
Object obj = null;
try {
if (flag) {
obj = joinPoint.proceed();
}else{
String result = JSONObject.fromObject(ResultUtil.success1(100, "failure")).toString();
output(response, result);
}
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("flag=" + flag + ",obj=" + obj);
return obj;
}

public void output(HttpServletResponse response, String msg) throws IOException {
response.setContentType("application/json;charset=UTF-8");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(msg.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
outputStream.flush();
outputStream.close();
}
}
}

测试controller类

import com.simons.cn.springbootdemo.aspect.RateLimitAspect;
import com.simons.cn.springbootdemo.util.ResultUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* 类描述:RateLimit限流测试(基于 注解+切面 方式)
* 创建人:simonsfan
*/
@Controller
public class TestController {

@ResponseBody
@RateLimitAspect //可以非常方便的通过这个注解来实现限流
@RequestMapping("/test")
public String test(){
return ResultUtil.success1(1001, "success").toString();
}

这样通过自定义注解@RateLimiterAspect来动态的加到需要限流的接口上,个人认为是比较优雅的实现吧。

压测结果:

打开网易新闻 查看更多图片

图片

可以看到,10个线程中无论压测多少次,并发数总是限制在6,也就实现了限流。

你还有什么想要补充的吗?

PS:欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。

版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢!

欢迎加入后端架构师,在后台回复“”即可。

最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。在这里,我为大家准备了一份2021年最新最全BAT等大厂Java面试经验总结。

别找了,想获取史上最简单的Java大厂面试题学习资料

扫下方二维码回复「面试」就好了

嘿,你在看吗?