0x01,感悟
好早之前写的一篇文章了,当时的感悟是,为什么要一直写文章呢?我也不知道,可能是为了将自己的内容做下总结吧,其实写的文章可能会用的很少,因为现在的项目基本上都有成熟的框架了,全新搭建一个项目或许很少,所以总觉得写了也没有什么意义,但是就是为了总结一下,以后用这些文章的时候可以翻阅查找。
0x02,文章整理
这篇文章的内容是自己在18年的时候写了一下示例程序,但是没有将它整理成文章,所以这里就简单整理了一下,顺便用了一下测试工具jmeter,很简单,毕竟不是专业的测试工具,若后面需要再继续看下jmeter的用法吧,这里就先有个概念。
0x03,拦截器和限流组件的整合
本文基于拦截器和guava提供的Ratelimiter进行请求的限流的示例程序的模拟的,文章整合起来很简单,限流主要为了防止过量的请求对服务器造成的压力而拒绝服务了,所以这里就简单模拟了一下,具体的示例程序如下。
0x04,需要的jar包依赖信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
0x05,示例程序
其次就是编写拦截器和注册拦截器的示例程序了。
package com.wpw.springbootratelimiter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class AbstractIntercepter extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return preHandle(request);
}
protected abstract boolean preHandle(HttpServletRequest request);
}
package com.wpw.springbootratelimiter;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
public class RatelimiterInterceptor extends AbstractIntercepter {
private static final RateLimiter rateLimiter = RateLimiter.create(1);
@Override
protected boolean preHandle(HttpServletRequest request) {
if (!rateLimiter.tryAcquire()) {
System.out.println("稍后重试");
return false;
}
System.out.println("获取许可成功");
return true;
}
}
package com.wpw.springbootratelimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class WebMvcConfigurationSupport implements WebMvcConfigurer {
@Autowired
private RatelimiterInterceptor ratelimiterInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(ratelimiterInterceptor);
}
}
package com.wpw.springbootratelimiter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wpw
*/
@RestController
public class UserController {
@GetMapping(value = "/hello")
public String hello() {
return "access success";
}
}
0x06,测试工具的使用
测试程序可以基于postman测试工具测试,不过为了模拟并发的请求,这里采用了jemeter进行了测试,截个图,不会jemeter的可以自己看下教程,这里就不做演示了。
看到后台的日志信息打印,发现了下面的重试信息的输出,说明我们的限流作用起作用了
0x07,总结
理解限流可以去理解火车站排队的场景或者去景点玩的场景,这里就不过多介绍了,这里自己就是为了总结一下和回顾一下自己的知识点,梳理一下。