SpringBoot利用Guava实现单机app限流访问
物料准备:
1.引入Guava依赖
2.定义一个限流注解作用于api接口的方法上
3.定义一个切面,对注解标注的方法实现一个限流访问文章来源:https://www.toymoban.com/news/detail-515411.html
引入Guava依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
定义注解@RateLimitAspect
package com.example.demo.service.guava;
import java.lang.annotation.*;
@Inherited
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimitAspect {
}
定义对应的处理的AOP逻辑
package com.example.demo.service.guava;
import com.alibaba.fastjson.JSON;
import com.example.demo.web.AjaxPubResponse;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class RateLimitAop {
@Autowired
private HttpServletResponse response;
@Pointcut("@annotation(com.example.demo.service.guava.RateLimitAspect)")
public void serviceLimit() {
}
private RateLimiter rateLimiter = RateLimiter.create(5.0); //比如说,我这里设置"并发数"为5
@Around("serviceLimit()")
public Object around(ProceedingJoinPoint joinPoint) {
Boolean flag = rateLimiter.tryAcquire();
Object obj = null;
try {
if (flag) {
obj = joinPoint.proceed();
}else{
String result = JSON.toJSONString(AjaxPubResponse.error("2003", "未获取到许可"));
// String result = JSONObject.fromObject(AjaxPubResponse.error("100", "failure")).toString();
output(response, result);
}
} catch (Throwable e) {
e.printStackTrace();
}
log.info("flag={},obj={}",flag,obj);
// 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();
}
}
}
使用方法,把@RateLimitAspect 注解添加到需要限流的API接口上即可,如
添加到@GetMapping 或 @PostMapping上文章来源地址https://www.toymoban.com/news/detail-515411.html
到了这里,关于SpringBoot利用Guava实现单机app限流访问的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!