從最簡(jiǎn)單的考慮我們只需要:1.一個(gè)servlet容器睛挚。2.處理請(qǐng)求轉(zhuǎn)發(fā)的servlet篮灼。
這里使用內(nèi)嵌Jetty + smiley-http-proxy-servlet棚辽。
pom.xml
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.4.11.v20180605</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.4.11.v20180605</version>
</dependency>
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
App.java
public class App {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/proxy");
HttpServlet proxyServlet = new ProxyServlet();
ServletHolder servletHolder = new ServletHolder();
servletHolder.setServlet(proxyServlet);
servletHolder.setInitParameter("targetUri", "https://www.baidu.com");
servletContextHandler.addServlet(servletHolder, "/baidu/*");
server.start();
}
}
然后來測(cè)試一下
瀏覽器輸入
http://localhost:8080/proxy/baidu
嗯跳到了百度首頁(yè)兢孝,
輸入http://localhost:8080/proxy/baidu/balabala
還是百度的頁(yè)面浇坐。
站在巨人的肩上我們只需要不到十行代碼就可以實(shí)現(xiàn)一個(gè)簡(jiǎn)易版反向代理服務(wù)器睬捶。
嗯下一步打算擴(kuò)展成可配置,代理多個(gè)地址的吗跋。