SpringBoot实现反向代理

作者 |47号Gamer丶
来源 | urlify.cn/uyaAri
第一步:相关依赖org.mitre.dsmiley.httpproxysmiley-http-proxy-servlet1.7com.google.guavaguava18.0第二步:配置文件# 代理的本地路由规则proxy.servlet_url: /api/*# 要代理的地址proxt.target_url: 第三步:import com.google.common.collect.ImmutableMap;import org.mitre.dsmiley.httpproxy.ProxyServlet;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; import javax.servlet.Servlet;import java.util.Map; /** * @ClassName: SolrProxyServletConfiguration * @Description: 反向代理 * @author: 47 * @date: 2020年03月24日 12:11 */@Configurationpublic class SolrProxyServletConfiguration {/*** 读取配置文件中路由设置*/@Value("${proxy.servlet_url}")private String servletUrl;/*** 读取配置中代理目标地址*/@Value("${proxy.target_url}")private String targetUrl;@Beanpublic Servlet createProxyServlet(){// 创建新的ProxyServletreturn new ProxyServlet();}@Beanpublic ServletRegistrationBean proxyServletRegistration(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(createProxyServlet(), servletUrl);//设置网址以及参数Map params = ImmutableMap.of("targetUri", targetUrl,"log", "true");registrationBean.setInitParameters(params);return registrationBean;}}
SpringBoot实现反向代理文章插图
import com.google.common.collect.ImmutableMap;import org.mitre.dsmiley.httpproxy.ProxyServlet;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; import javax.servlet.Servlet;import java.util.Map; /** * @ClassName: SolrProxyServletConfiguration * @Description: 反向代理 * @author: 47 * @date: 2020年03月24日 12:11 */@Configurationpublic class SolrProxyServletConfiguration {/*** 读取配置文件中路由设置*/@Value("${proxy.servlet_url}")private String servletUrl;/*** 读取配置中代理目标地址*/@Value("${proxy.target_url}")private String targetUrl;@Beanpublic Servlet createProxyServlet(){// 创建新的ProxyServletreturn new ProxyServlet();}@Beanpublic ServletRegistrationBean proxyServletRegistration(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(createProxyServlet(), servletUrl);//设置网址以及参数Map params = ImmutableMap.of("targetUri", targetUrl,"log", "true");registrationBean.setInitParameters(params);return registrationBean;}}第四步:测试效果【SpringBoot实现反向代理】访问本地请求localhost:/api,可以看到已经代理到我们的目标地址了百度首页了