Spring Netflix Zuul:API-Gateway - 转换JSON请求

时间:2018-01-12 16:15:49

标签: json api spring-boot netflix-zuul api-gateway

我目前正在使用Spring Netflix Zuul库为新的微服务系统构建API网关。

到目前为止,我的网关包含PREPOST过滤器,可拦截请求并执行所需的逻辑等。

我看到的一件事是REST调用特定的微服务需要调用包含非常复杂的JSON有效负载数据的API端点(GET或POST)。

对于向包含此JSON的微服务发送请求的最终用户来说,用户不会友好。

我有一个想法,API网关充当中介,用户可以向API网关提交更“简化/用户友好”的JSON,这将使用正确的“复杂”JSON转换JSON有效负载目标微服务可以理解的结构,以便有效地处理请求。

我对Netflix Zuul的理解是,可以通过创建RouteFilter然后在此处包含此逻辑来完成此操作。

任何人都可以解释是否(或如何)使用Netflix Zuul进行此转换?

感谢任何建议。

感谢。

2 个答案:

答案 0 :(得分:0)

毫无疑问,你可以用Zuul做到这一点,我现在正试图做同样的事情。我建议你看看这个回购:

sample-zuul-filters

和github上的official doc

过滤器必须扩展ZuulFilter并实现以下方法:

/** 
 *return a string defining when your filter must execute during zuul's
 *lyfecyle ('pre'/'post' routing 
 **/
@Override
public String filterType(){

   return 'pre';  // run this filter before sending the final request
}

/** 
 * return an int describing the order that the filter should run on,  
 *  (relative to the other filters and the current 'pre' or 'post' context)
 **/
@Override
public int filterOrder {
    return 1; //this filter runs first in a pre-request context
}

/** 
 * return a boolean indicating if the filter should run or not
 **/
@Override
public boolean shouldFilter() {
    RequestContext ctx = RequestContext.getCurrentContext();

    if(ctx.getRequest().getRequestURI().equals("/theRouteIWantToFilter"))
    {
        return true;
    }
    else {
        return false;
    }
}

/**
 * After all the config stuffs you can set what your filter actually does 
 * here. This is where your json logic goes. 
 */
@Override
public Object run() {
    try {
     RequestContext ctx = RequestContext.getCurrentContext();
     HttpServletRequest request = ctx.getRequest();
     InputStream stream = ctx.getResponseDataStream();
     String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));

     // transform your json and send it to the api. 

     ctx.setResponseBody(" Modified body :  " + body);
    } catch (IOException e) {
        e.printStackTrace();
    }
     return null; 
}

我不确定我的回答是100%准确,因为我从事这项工作,但这是一个开始。

答案 1 :(得分:0)

我已经在预过滤器中完成了有效负载转换,但这也适用于路由过滤器。在将请求转发到目标微服务之前,使用 com.netflix.zuul.http.HttpServletRequestWrapper 来捕获和修改原始请求有效负载。

示例代码:

package com.sample.zuul.filters.pre;

import com.google.common.io.CharStreams;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class JsonConverterFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0; //  Set it to whatever the order of your filter is
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = new HttpServletRequestWrapper(context.getRequest());

        String requestData = null;
        JSONParser jsonParser = new JSONParser();
        JSONObject requestJson = null;

        try {
            if (request.getContentLength() > 0) {
                requestData = CharStreams.toString(request.getReader());
            }
            if (requestData == null) {
                return null;
            }
            requestJson = (JSONObject) jsonParser.parse(requestData);
        } catch (Exception e) {
            //Add your exception handling code here
        }

        JSONObject modifiedRequest = modifyJSONRequest(requestJson);

        final byte[] newRequestDataBytes = modifiedRequest.toJSONString().getBytes();

        request = getUpdatedHttpServletRequest(request, newRequestDataBytes);
        context.setRequest(request);
        return null;
    }



    private JSONObject modifyJSONRequest(JSONObject requestJSON) {

        JSONObject jsonObjectDecryptedPayload = null;
        try {
            jsonObjectDecryptedPayload = (JSONObject) new JSONParser()
                    .parse("Your new complex json");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return jsonObjectDecryptedPayload;
    }


    private HttpServletRequest getUpdatedHttpServletRequest(HttpServletRequest request, final byte[] newRequestDataBytes) {
        request = new javax.servlet.http.HttpServletRequestWrapper(request) {

            @Override
            public BufferedReader getReader() throws IOException {
                return new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(newRequestDataBytes)));
            }

            @Override
            public ServletInputStream getInputStream() throws IOException {
                return new ServletInputStreamWrapper(newRequestDataBytes);
            }
         /*
             * Forcing any calls to HttpServletRequest.getContentLength to return the accurate length of bytes
             * from a modified request
             */
            @Override
            public int getContentLength() {
                return newRequestDataBytes.length;
            }
        };
        return request;
    }
}