在Spring应用调试中实现反向代理服务器
运行反向代理服务器
注:目前我们使用8888端口,如果需要更改,可以修改src/main/resources/application.properties文件的server.port属性。
我们就是百度
打开浏览器,访问,发现我们进入到了百度首页,进行搜索、翻页等操作,发现行为和百度一模一样,但是域名仍然是我们的localhost:8080。接下来,我们来看看如何达到这样的效果。
首先是添加依赖,除了Spring-boot最基本依赖外,我们还依赖了两个库,一个是Google的guava库,里面包含了Google的很多核心库,我们主要使用其中的集合。另一个是代理的核心库smiley-http-proxy-servlet,是github上的一个开源项目:
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
引入依赖后,我们只需要声明一个proxy的servlet,并对其进行配置即可:
@Bean
public Servlet baiduProxyServlet(){
return new ProxyServlet();
}
@Bean
public ServletRegistrationBean proxyServletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(baiduProxyServlet(), "/*");
Map<String, String> params = ImmutableMap.of(
"targetUri", "http://baidu.com",
"log", "true");
registrationBean.setInitParameters(params);
return registrationBean;
}
我们可以看到,只需要对targetURi进行设置,表明ProxyServlet需要代理,然后将所有/*交给baiduProxyServlet()进行处理即可。
上一篇:
IDEA上Java项目控制台中文乱码
