正常情況下被限流會自動返回
狀態碼爲429,消息體爲:
{
"timestamp": 1560396819329,
"status": 429,
"error": "Too Many Requests",
"exception": "com.netflix.zuul.exception.ZuulException",
"message": "429"
}
下面它變成狀態碼爲200,消息體自定義:
我是在zuul網關下建立一個全局返回狀態監聽:繼承 org.springframework.boot.autoconfigure.web.DefaultErrorAttributes 並且重寫了 getErrorAttributes 方法:
package io.spring.cloud.zuul.demo;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import java.util.HashMap;
import java.util.Map;
@Component
public class DemoErrorAttribute extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> result = super.getErrorAttributes(requestAttributes, includeStackTrace);
//不是狀態碼429就不用自定義返回處理;
if(!result.get("status").equals(429)){
return result;
}
//修改返回狀態碼爲200
requestAttributes.setAttribute("javax.servlet.error.status_code",200,RequestAttributes.SCOPE_REQUEST);
//自定義消息體 需要返回一個map,如果是實體類,可以轉爲map再返回
Map<String,Object> map = new HashMap<>();
map.put("code","429");
map.put("message","請勿頻繁請求");
return map;
}
}
運行後觸發429後返回的就是一個狀態爲200的消息體爲:
{
"code": "429",
"message": "請勿頻繁請求"
}
注:不單單是狀態碼是429,500之類的也可以處理