爷的眼睛闪亮
insideDotNet En_summerGarden
<!--限流-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>16.0.1</version>
</dependency>
============================================================================
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {

double limitNum() default 20; //速率

}
============================================================================
@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.yunting.consumer.sandconsumer.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(Result.build(500, "慢点,慢点,太快了!"));
log.error("拒绝了请求:" + 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);
}

}

============================================================================
@PostMapping("/user/xx/xx")
@RateLimit(limitNum = 100)
public Result gitftConsume(@RequestBody GiftConsumeDto giftConsumeDto)


posted on 2020-07-01 16:00  爷的眼睛闪亮  阅读(310)  评论(0编辑  收藏  举报