springboot实现反向代理,监听服务调用
已知一个第三方服务,如何在调用这个第三方服务之前,通过反向代理的方式,屏蔽第三方服务地址,并且监听其服务调用情况和做一些其他的事情呢。
1.引入包
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
2.创建配置类
@Configuration
public class SolrProxyServletConfiguration {
// 读取配置文件中路由设置
private String servlet_url="/proxy/*";
// 读取配置中代理目标地址
private String target_url="https://www.baidu.com";
@Bean
public Servlet createProxyServlet(){
// 创建新的ProxyServlet
return new MyProxyServlet();
}
@Bean
public ServletRegistrationBean proxyServletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(createProxyServlet(), servlet_url);
//设置网址以及参数
Map<String, String> params = ImmutableMap.of("targetUri", target_url,"log", "true");
registrationBean.setInitParameters(params);
return registrationBean;
}
}
3.创建MyProxyServlet类,继承ProxyServlet,并重写doExecute,在doExecute就可以监听服务与控制服务调用了
public class MyProxyServlet extends ProxyServlet {
@Override
protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpRequest proxyRequest) throws IOException {
super.doLog=false;//关闭父类的日志输出
proxyRequest.setHeader("Authorization", "Basic " + "aaaaa");
HttpResponse response = super.doExecute(servletRequest, servletResponse, proxyRequest);
System.out.println("这里进行权限控制和输出日志。。。。。。。。。。。,代理地址222222(proxy):"+ servletRequest.getMethod() + " uri: " + " -- " + proxyRequest.getRequestLine().getUri());
// 设置跨域,暂时不用。
// String origin = servletRequest.getHeader("origin");
// response.setHeader("Access-Control-Allow-Origin", origin);
// response.setHeader("Access-Control-Allow-Credentials", "true");
// response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
// response.setHeader("Access-Control-Allow-Headers",
// "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin" +
// ",User-Agent,X-Mx-ReqToken,X-Requested-With");
return response;
}
}
4.测试
浏览器访问:http://localhost:8083/proxy 就会被springboot获取,并代理成 https://www.baidu.com
注意,如果访问:http://localhost:8083/proxy/xxxxxx 就会被springboot获取,并代理成 https://www.baidu.com/xxxxxx