use of com.cloud.common.exception.RateLimiterException in project new-cloud by xie-summer.
the class RedisRateLimitZuulFilter method run.
@Override
public Object run() {
try {
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletResponse response = currentContext.getResponse();
if (!redisTemplate.hasKey(TIME_KEY)) {
redisTemplate.opsForValue().set(TIME_KEY, 0, 1, TimeUnit.SECONDS);
}
if (redisTemplate.hasKey(TIME_KEY) && redisTemplate.opsForValue().increment(COUNTER_KEY, 1) > 400) {
HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
response.setStatus(httpStatus.value());
response.getWriter().append(httpStatus.getReasonPhrase());
currentContext.setSendZuulResponse(false);
throw new RateLimiterException(httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase());
}
} catch (Throwable e) {
ReflectionUtils.rethrowRuntimeException(e);
}
return null;
}
use of com.cloud.common.exception.RateLimiterException in project new-cloud by xie-summer.
the class ServiceRateLimitZuulFilter method run.
@Override
public Object run() {
try {
RequestContext context = RequestContext.getCurrentContext();
HttpServletResponse response = context.getResponse();
String key = null;
// 对于service格式的路由,走RibbonRoutingFilter
String serviceId = (String) context.get(SERVICE_ID_KEY);
if (serviceId != null) {
key = serviceId;
map.putIfAbsent(serviceId, RateLimiter.create(1000.0));
} else // 如果压根不走RibbonRoutingFilter,则认为是URL格式的路由
{
// 对于URL格式的路由,走SimpleHostRoutingFilter
URL routeHost = context.getRouteHost();
if (routeHost != null) {
String url = routeHost.toString();
key = url;
map.putIfAbsent(url, RateLimiter.create(2000.0));
}
}
RateLimiter rateLimiter = map.get(key);
if (!rateLimiter.tryAcquire()) {
HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
response.setStatus(httpStatus.value());
response.getWriter().append(httpStatus.getReasonPhrase());
context.setSendZuulResponse(false);
throw new RateLimiterException(httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase());
}
} catch (Exception e) {
ReflectionUtils.rethrowRuntimeException(e);
}
return null;
}
Aggregations