异常枚举 @Getter public enum ExceptionEnum { RATERLIMIT_NO(1, "暂时没有获取到令牌,请稍后再试"),; private Integer code; private String message; ExceptionEnum(Integer code, String message) { this.code = code; this.message = message; } }
自定义限流异常
public class RateLimitException extends RuntimeException { private Integer code; public RateLimitException(int code, String message) { super(message); this.code = code; } }
限流过滤器
@Component public class RateLimitFilter extends ZuulFilter { private static final RateLimiter RATE_LIMITER = RateLimiter.create(1); @Override public String filterType() { return PRE_TYPE; } @Override public int filterOrder() { return SERVLET_DETECTION_FILTER_ORDER - 1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { if (!RATE_LIMITER.tryAcquire()) { throw new RateLimitException(ExceptionEnum.RATERLIMIT_NO.getCode() , ExceptionEnum.RATERLIMIT_NO.getMessage()); } return null; } }
测试结果
{ "timestamp": 1531967665138, "status": 500, "error": "Internal Server Error", "exception": "com.netflix.zuul.exception.ZuulException", "message": "pre:RateLimitFilter" }
疑问:为什么抛出的异常不是自定义的异常,message不应该是自定义的“暂时没有获取到令牌,请稍后再试
”信息么??师兄能解惑一下么?感谢师兄
SpringCloud组件实现微服务,【已升级Finchley.Release】
了解课程