Spring Netflix Zuul:API网关-转换JSON请求

Spring Netflix Zuul:API网关-转换JSON请求,json,api,spring-boot,netflix-zuul,api-gateway,Json,Api,Spring Boot,Netflix Zuul,Api Gateway,我目前正在使用Spring Netflix Zuul库为一个新的微服务系统构建一个API网关 到目前为止,我的网关包含拦截请求并执行所需逻辑等的PRE和POST过滤器 我看到的一件事是,对特定微服务的REST调用需要调用包含非常复杂的JSON负载数据的API端点(GET或POST) 对于最终用户来说,向包含此JSON的微服务发送请求并不友好 我的想法是,API网关充当中介,用户可以向API网关提交一个更“简化/用户友好”的JSON,这将使用目标微服务可以理解的正确“复杂”JSON结构转换JSON

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

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

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

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

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

我对Netflix Zuul的理解是,这可以通过创建一个
RouteFilter
然后将此逻辑包含在这里来实现

有人能解释一下,使用Netflix Zuul是否可以(或如何)实现这一转变吗

任何建议都将不胜感激


谢谢。

毫无疑问,你可以用Zuul来做,我现在也在尝试做同样的事情。我建议你看看这个回购协议:

和github上的

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

/** 
 *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%准确,因为我正在努力,但这只是一个开始

我已经在pre filter中完成了有效负载转换,但这也应该在route filter中起作用。在将请求转发到目标微服务之前,使用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;
    }
}

这与我最近提出的问题基本相同(),我在其中提到了netflix zuul。我几乎采用了同样的方法来回答这个问题。我唯一担心的是适配器的实现会有点复杂(例如,一个产品中会有很多POST服务,识别当前正在处理的POST有点棘手)。