欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring boot实现超轻量级网关(反向代理、转发)

程序员文章站 2022-08-27 13:33:54
在我们的rest服务中,需要暴露一个中间件的接口给用户,但是需要经过rest服务的认证,这是典型的网关使用场景。可以引入网关组件来搞定,但是引入zuul等中间件会增加系统复杂性,这里实现一个超轻量级的...

在我们的rest服务中,需要暴露一个中间件的接口给用户,但是需要经过rest服务的认证,这是典型的网关使用场景。可以引入网关组件来搞定,但是引入zuul等中间件会增加系统复杂性,这里实现一个超轻量级的网关,只实现请求转发,认证等由rest服务的spring security来搞定。

如何进行请求转发呢? 熟悉网络请求的同学应该很清楚,请求无非就是请求方式、http header,以及请求body,我们将这些信息取出来,透传给转发的url即可。

举例:

/graphdb/** 转发到 graph_server/**

获取转发目的地址:

private string createredicturl(httpservletrequest request, string routeurl, string prefix) {
    string querystring = request.getquerystring();
    return routeurl + request.getrequesturi().replace(prefix, "") +
        (querystring != null ? "?" + querystring : "");
  }

 

解析请求头和内容

然后从request中提取出header、body等内容,构造一个requestentity,后续可以用resttemplate来请求。

private requestentity createrequestentity(httpservletrequest request, string url) throws urisyntaxexception, ioexception {
    string method = request.getmethod();
    httpmethod httpmethod = httpmethod.resolve(method);
    multivaluemap<string, string> headers = parserequestheader(request);
    byte[] body = parserequestbody(request);
    return new requestentity<>(body, headers, httpmethod, new uri(url));
  }


  private byte[] parserequestbody(httpservletrequest request) throws ioexception {
    inputstream inputstream = request.getinputstream();
    return streamutils.copytobytearray(inputstream);
  }

  private multivaluemap<string, string> parserequestheader(httpservletrequest request) {
    httpheaders headers = new httpheaders();
    list<string> headernames = collections.list(request.getheadernames());
    for (string headername : headernames) {
      list<string> headervalues = collections.list(request.getheaders(headername));
      for (string headervalue : headervalues) {
        headers.add(headername, headervalue);
      }
    }
    return headers;
  }

透明转发

最后用resttemplate来实现请求:

 private responseentity<string> route(requestentity requestentity) {
    resttemplate resttemplate = new resttemplate();
    return resttemplate.exchange(requestentity, string.class);
  }

全部代码

以下是轻量级转发全部代码:

import org.springframework.http.*;
import org.springframework.stereotype.service;
import org.springframework.util.multivaluemap;
import org.springframework.util.streamutils;
import org.springframework.web.client.resttemplate;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
import java.io.inputstream;
import java.net.uri;
import java.net.urisyntaxexception;
import java.util.collections;
import java.util.list;

@service
public class routingdelegate {


  public responseentity<string> redirect(httpservletrequest request, httpservletresponse response,string routeurl, string prefix) {
    try {
      // build up the redirect url
      string redirecturl = createredicturl(request,routeurl, prefix);
      requestentity requestentity = createrequestentity(request, redirecturl);
      return route(requestentity);
    } catch (exception e) {
      return new responseentity("redirect error", httpstatus.internal_server_error);
    }
  }

  private string createredicturl(httpservletrequest request, string routeurl, string prefix) {
    string querystring = request.getquerystring();
    return routeurl + request.getrequesturi().replace(prefix, "") +
        (querystring != null ? "?" + querystring : "");
  }


  private requestentity createrequestentity(httpservletrequest request, string url) throws urisyntaxexception, ioexception {
    string method = request.getmethod();
    httpmethod httpmethod = httpmethod.resolve(method);
    multivaluemap<string, string> headers = parserequestheader(request);
    byte[] body = parserequestbody(request);
    return new requestentity<>(body, headers, httpmethod, new uri(url));
  }
	
  private responseentity<string> route(requestentity requestentity) {
    resttemplate resttemplate = new resttemplate();
    return resttemplate.exchange(requestentity, string.class);
  }


  private byte[] parserequestbody(httpservletrequest request) throws ioexception {
    inputstream inputstream = request.getinputstream();
    return streamutils.copytobytearray(inputstream);
  }

  private multivaluemap<string, string> parserequestheader(httpservletrequest request) {
    httpheaders headers = new httpheaders();
    list<string> headernames = collections.list(request.getheadernames());
    for (string headername : headernames) {
      list<string> headervalues = collections.list(request.getheaders(headername));
      for (string headervalue : headervalues) {
        headers.add(headername, headervalue);
      }
    }
    return headers;
  }
}

spring 集成

spring controller,requestmapping里把get \ post\put\delete 支持的请求带上,就能实现转发了。

@restcontroller
@requestmapping(graphdbcontroller.delegate_prefix)
@api(value = "graphdb", tags = {
    "graphdb-api"
})
public class graphdbcontroller {

  @autowired
  graphproperties graphproperties;

  public final static string delegate_prefix = "/graphdb";

  @autowired
  private routingdelegate routingdelegate;

  @requestmapping(value = "/**", method = {requestmethod.get, requestmethod.post, requestmethod.put, requestmethod.delete}, produces = mediatype.text_plain_value)
  public responseentity catchall(httpservletrequest request, httpservletresponse response) {
    return routingdelegate.redirect(request, response, graphproperties.getgraphserver(), delegate_prefix);
  }
}

到此这篇关于spring boot实现超轻量级网关(反向代理、转发)的文章就介绍到这了,更多相关spring boot轻量级网关内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!