springboot实现反向代理,动态代理目标地址
网上找了很多文章,各种照搬,只能自己实现
基于开源项目HTTP-Proxy-Servlet实现
开源项目地址:https://github.com/mitre/HTTP-Proxy-Servlet
1. 添加依赖
<dependency> <groupId>org.mitre.dsmiley.httpproxy</groupId> <artifactId>smiley-http-proxy-servlet</artifactId> <version>1.11</version> </dependency>
2. 实现自己的ProxyServlet,重写service方法,官方通过配置servlet参数只能代理一个目标地址,通过自己拓展service方法,进行逻辑判断可以动态代理到不同的目标地址,参考代码如下:
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String targetUri = "http://www.baidu.com/"; servletRequest.setAttribute(ATTR_TARGET_URI, null); super.targetUri = targetUri; URI uri = null; try { uri = new URI(targetUri); } catch (URISyntaxException e) { log.error("创建URI对象出错, targetUri[{}]", targetUri, e); } servletRequest.setAttribute(ATTR_TARGET_HOST, null); super.targetHost = URIUtils.extractHost(uri); super.service(servletRequest, servletResponse); }
3. springboot中注册servlet,参考代码如下:
@Configuration public class ProxyServletConfiguration { @Bean public ServletRegistrationBean<DiskProxyServlet> servletServletRegistrationBean() { ServletRegistrationBean<DiskProxyServlet> servletRegistrationBean = new ServletRegistrationBean<>(new DiskProxyServlet(), "/toProxy"); servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, "true"); return servletRegistrationBean; } }
4. 浏览器访问http://ip:port/toProxy,会代理到百度首页;