zoukankan      html  css  js  c++  java
  • 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,会代理到百度首页;

  • 相关阅读:
    nginx-consul-template
    安装calico
    安装docker
    etcd集群安装
    安装consul-client+registrator
    command not found 的解决&&解释
    安装consul
    RAC环境下SCAN IP可以PING通,1521端口也可以TELNET,但是无法建立数据库连接
    Error starting daemon: error initializing graphdriver: devmapper: Device docker-thinpool is not a thin pool
    nginx+keepalived高可用
  • 原文地址:https://www.cnblogs.com/changxy-codest/p/13093132.html
Copyright © 2011-2022 走看看