spring cloud zuul ratelimit 限流实现自定义数据返回

正常情况下被限流会自动返回

状态码为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 getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map 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 map = new HashMap<>();
        map.put("code","429");
        map.put("message","请勿频繁请求");
        return map;
    }
}

 运行后触发429后返回的就是一个状态为200的消息体为:

{
"code": "429",
"message": "请勿频繁请求"
}

注:不单单是状态码是429,500之类的也可以处理

你可能感兴趣的:(spring,cloud)