我正在尝试使用 jetty7 构建透明代理设置。想法是将源服务器隐藏在码头服务器后面,以便可以将传入的请求以透明的方式转发到源服务器。
我想知道我是否可以使用码头的 ProxyServlet.Transparent 实现来做到这一点。如果是的话,谁能给我一些例子。
我正在尝试使用 jetty7 构建透明代理设置。想法是将源服务器隐藏在码头服务器后面,以便可以将传入的请求以透明的方式转发到源服务器。
我想知道我是否可以使用码头的 ProxyServlet.Transparent 实现来做到这一点。如果是的话,谁能给我一些例子。
此示例基于 Jetty-9。如果你想用 Jetty 8 实现它,请实现 proxyHttpURI 方法(参见 Jetty 8 javadocs。)。这是一些示例代码。
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.servlets.ProxyServlet;
/**
* When a request cannot be satisfied on the local machine, it asynchronously
* proxied to the destination box. Define the rule
*/
public class ContentBasedProxyServlet extends ProxyServlet {
private int remotePort = 8080;
public void setPort(int port) {
this.remotePort = port;
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
super.service(request, response);
}
/**
* Applicable to Jetty 9+ only.
*/
@Override
protected URI rewriteURI(HttpServletRequest request) {
String proxyTo = getProxyTo(request);
if (proxyTo == null)
return null;
String path = request.getRequestURI();
String query = request.getQueryString();
if (query != null)
path += "?" + query;
return URI.create(proxyTo + "/" + path).normalize();
}
private String getProxyTo(HttpServletRequest request) {
/*
* Implement this method: All the magic happens here. Use this method to figure out your destination machine address. You can maintain
* a static list of addresses, and depending on the URI or request content you can route your request transparently.
*/
}
}
此外,您可以实现一个过滤器来确定请求是需要在本地机器上还是在目标机器上终止。如果请求是针对远程机器的,则将请求转发到此 servlet。
// Declare this method call in the filter.
request.getServletContext()
.getNamedDispatcher("ContentBasedProxyServlet")
.forward(request, response);