• 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,会代理到百度首页;

  • 相关阅读:
    Django之Form组件
    随笔——python截取http请求报文响应头
    django文件上传
    django框架(View)
    s15day14 ssh秘钥远程连接
    Python开发【第十九篇】:Python操作MySQL
    s15day12作业:MySQL练习题参考答案
    python+django+wusgi+nginx安装部署
    Python之路【第二十四篇】:Python学习路径及练手项目合集
    gideros-with-zerobrane
  • 原文地址:https://www.cnblogs.com/changxy-codest/p/13093132.html
Copyright © 2020-2023  润新知