使用 jetty-proxy 实现反向代理

发布时间 2023-07-25 13:56:42作者: Nihaorz

pom.xml

<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-proxy</artifactId>
    <version>9.4.51.v20230217</version>
</dependency>

 

JettyReverseProxyServletConfig.java

package com.geostar.geoonline.server.framework.configuration;

import org.eclipse.jetty.proxy.AsyncProxyServlet;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.geostar.geoonline.server.framework.configuration.JettyReverseProxyServletConfig.ReverseProxyServlet.MAX_THREADS;
import static com.geostar.geoonline.server.framework.configuration.JettyReverseProxyServletConfig.ReverseProxyServlet.TARGET_URI;

@Configuration
public class JettyReverseProxyServletConfig implements ServletContextInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        ServletRegistration initServlet = servletContext.addServlet("sc", ReverseProxyServlet.class);
        initServlet.addMapping("/scProxy/*");
        initServlet.setInitParameter(MAX_THREADS, "10");
        initServlet.setInitParameter(TARGET_URI, "http://172.19.2.70:9010/ServiceCenter");
    }


    public static class ReverseProxyServlet extends AsyncProxyServlet {

        public static final String MAX_THREADS = "maxThreads";

        public static final String TARGET_URI = "TARGET_URI";

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 解决 java.lang.IllegalStateException: A filter or servlet of the current chain does not support asynchronous operations.
            request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
            super.service(request, response);
        }

        @Override
        protected String rewriteTarget(HttpServletRequest clientRequest) {
            if (!validateDestination(clientRequest.getServerName(), clientRequest.getServerPort())) {
                return null;
            }
            StringBuilder target = new StringBuilder();
            String targetUri = getInitParameter(TARGET_URI);
            if (targetUri.endsWith("/")) {
                targetUri.substring(0, targetUri.length() - 1);
            }
            target.append(targetUri).append(clientRequest.getPathInfo());
            String query = clientRequest.getQueryString();
            if (query != null) {
                target.append("?").append(query);
            }
            return target.toString();
        }
    }

}