java的http代理已经存在可以直接使用的库, smiley-http-proxy-servlet,原理就是copy请求,进行转发 需求有点类似网关的功能,就是对请求进行前置与后置处理,不想引入springcloud与springgateway,所以就需要对smiley-http-proxy-servlet做一些封装 a. 主要是需要手动注册多个servlet,监听一些请求, b. Servlet在执行service方法时,可改写请求参数 c. Servlet在执行service方法后, 对servletRequest与servletResponse进行copy, d. 做一些业务处理
- 引入smiley-http-proxy-servlet库
pom.xml
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.12.1</version>
</dependency>
- 配置监听的请求和转发的请求,
application.yml
proxy:
configs:
- servlet_url: /proxy/*
target_url: http://192.168.0.4:8401/handler1
- servlet_url: /proxy_1/*
target_url: http://192.168.0.141:9004/handler
logging_enabled: true
- servlet_url: /proxy_2/*
target_url: http://192.168.0.141:8400/handler2
logging_enabled: true
- 配置类
@Data
@ConfigurationProperties(prefix = "proxy")
@Component
public class ProxyConfig {
private List<ProxyProperties> configs;
@Data
public static class ProxyProperties {
private String servletUrl;
private String targetUrl;
private Boolean loggingEnabled =false;
}
}
- springboot 代码形式手动注册servlet
@Component
public class ServletConfig implements ServletContextInitializer{
private final ProxyConfig config;
@Autowired
public ServletConfig(ProxyConfig config){
this.config = config;
}
@Override
public void onStartup(ServletContext servletContext) {
List<ProxyConfig.ProxyProperties> propertiesList = config.getConfigs();
for (int i = 0; i < propertiesList.size(); i++) {
ProxyConfig.ProxyProperties properties = propertiesList.get(i);
//定义多个servlet
ServletRegistration initServlet = servletContext.addServlet("MyProxyServlet"+i, MyProxyServlet.class);
initServlet.addMapping(properties.getServletUrl());
initServlet.setInitParameter(ProxyServlet.P_TARGET_URI, properties.getTargetUrl());
initServlet.setInitParameter(ProxyServlet.P_LOG, properties.getLoggingEnabled().toString());
}
}
}
- 重写servlet, 获取请求,与结果,对其进行一些记录,或者
public class MyProxyServlet extends ProxyServlet {
private SourceController biddingController;
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
MyHttpServletRequestWrapper requestWrapper = new MyHttpServletRequestWrapper(servletRequest);
byte[] res = serviceV1(super.targetUri,requestWrapper,servletResponse);
this.doExtend(requestWrapper,res);
略....
}
}
- 重写ServletRequest类
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
...略
}
- 获取请求返回的结果,
使用smiley-http-proxy-servlet的ProxyServlet::copyResponseEntity方法即可
|