<!-- guava 限流 --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>25.1-jre</version> </dependency>
@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ServiceLimit { String description() default ""; }
@Component @Scope @Aspect public class LimitAspect { 每秒只发出5个令牌,此处是单进程服务的限流,内部采用令牌捅算法实现 private static RateLimiter rateLimiter = RateLimiter.create(5.0); //Service层切点 限流 @Pointcut("@annotation(com.itstyle.seckill.common.aop.ServiceLimit)") public void ServiceAspect() { } @Around("ServiceAspect()") public Object around(ProceedingJoinPoint joinPoint) { Boolean flag = rateLimiter.tryAcquire(); Object obj = null; try { if(flag){ obj = joinPoint.proceed(); } } catch (Throwable e) { e.printStackTrace(); } return obj; } }
1 Kebergantungan
@Override @ServiceLimit @Transactional public Result startSeckil(long seckillId,long userId) { //todo 操作 }
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.1-jre</version> <optional>true</optional> </dependency>
@Slf4j @Configuration public class RequestInterceptor implements HandlerInterceptor { // 根据字符串分不同的令牌桶, 每天自动清理缓存 private static LoadingCache<String, RateLimiter> cachesRateLimiter = CacheBuilder.newBuilder() .maximumSize(1000) //设置缓存个数 /** * expireAfterWrite是在指定项在一定时间内没有创建/覆盖时,会移除该key,下次取的时候从loading中取 * expireAfterAccess是指定项在一定时间内没有读写,会移除该key,下次取的时候从loading中取 * refreshAfterWrite是在指定时间内没有被创建/覆盖,则指定时间过后,再次访问时,会去刷新该缓存,在新值没有到来之前,始终返回旧值 * 跟expire的区别是,指定时间过后,expire是remove该key,下次访问是同步去获取返回新值; * 而refresh则是指定时间后,不会remove该key,下次访问会触发刷新,新值没有回来时返回旧值 */ .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, RateLimiter>() { @Override public RateLimiter load(String key) throws Exception { // 新的字符串初始化 (限流每秒2个令牌响应) return RateLimiter.create(2); } }); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("request请求地址path[{}] uri[{}]", request.getServletPath(), request.getRequestURI()); try { String str = "hello"; // 令牌桶 RateLimiter rateLimiter = cachesRateLimiter.get(str); if (!rateLimiter.tryAcquire()) { System.out.println("too many requests."); return false; } } catch (Exception e) { // 解决拦截器的异常,全局异常处理器捕获不到的问题 request.setAttribute("exception", e); request.getRequestDispatcher("/error").forward(request, response); } return true; } }
http://localhost:8080/user/
Jika tiada kelas hasil, anda boleh mengembalikan rentetan sesuka hati
4. Keputusan ujianLain-lain
Buat
RateLimiter menyediakan dua kaedah kilang:Satu adalah letusan lancar Mengehadkan arus
@RestController @RequestMapping(value = "user") public class UserController { @GetMapping public Result test2(){ System.out.println("1111"); return new Result(true,200,""); } }
RateLimiter r = RateLimiter.create(5); //项目启动,直接允许5个令牌
Keburukan
RateLimiter hanya boleh digunakan untuk pengehadan arus mesin tunggal, jika anda mahukan kluster Untuk pengehadan semasa, anda perlu memperkenalkan redis atau perisian tengah sentinel sumber terbuka Alibaba.
rreeeeAtas ialah kandungan terperinci Bagaimanakah SpringBoot menggunakan RateLimiter untuk mengehadkan arus melalui AOP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!