Java+springboot实现nginx反向代理功能

Posted 水木轩昊昊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java+springboot实现nginx反向代理功能相关的知识,希望对你有一定的参考价值。

一、功能描述


要实现的功能是

浏览器请求: http://127.0.0.1:8080/proxy/user

希望请求转发到 http://192.168.0.100:8084/user

二、配置文件


proxy.targetAddr=http://192.168.0.100:8084/


三、源码 

package com.biubiu.agent.controller;
 
import com.biubiu.agent.annotation.SystemLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
 
@Controller
public class ProxyController 
 
    @Value("$proxy.targetAddr")
    private String targetAddr;
 
    /**
     * 代理所有请求
     * @param request
     * @param response
     * @throws Exception
     */
    @SystemLog(description = "代理转发")
    @RequestMapping(value = "/proxy/**", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void proxy(HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException 
        // String url = URLDecoder.decode(request.getRequestURL().toString(), "UTF-8");
        URI uri = new URI(request.getRequestURI());
        String path = uri.getPath();
        String query = request.getQueryString();
        URI newUri = new URI(targetAddr + path.replace("/proxy", "") + "?" + query);
        // 执行代理查询
        String methodName = request.getMethod();
        HttpMethod httpMethod = HttpMethod.resolve(methodName);
        if(httpMethod == null) 
            return;
        
        ClientHttpRequest delegate = new SimpleClientHttpRequestFactory().createRequest(newUri, httpMethod);
        Enumeration<String> headerNames = request.getHeaderNames();
        // 设置请求头
        while (headerNames.hasMoreElements()) 
            String headerName = headerNames.nextElement();
            Enumeration<String> v = request.getHeaders(headerName);
            List<String> arr = new ArrayList<>();
            while (v.hasMoreElements()) 
                arr.add(v.nextElement());
            
            delegate.getHeaders().addAll(headerName, arr);
        
        StreamUtils.copy(request.getInputStream(), delegate.getBody());
        // 执行远程调用
        ClientHttpResponse clientHttpResponse = delegate.execute();
        response.setStatus(clientHttpResponse.getStatusCode().value());
        // 设置响应头
        clientHttpResponse.getHeaders().forEach((key, value) -> value.forEach(it -> 
            response.setHeader(key, it);
        ));
        StreamUtils.copy(clientHttpResponse.getBody(), response.getOutputStream());
    



四、当前springboot版本和pom文件参考

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


 

以上是关于Java+springboot实现nginx反向代理功能的主要内容,如果未能解决你的问题,请参考以下文章

Nginx视频教程 反向代理/https/openresty/lua实战

Nginx反代配置

Web服务器群集——部署Java项目,实现Nginx反向代理Tomcat服务器

Java+springboot实现nginx反向代理功能

Java+springboot实现nginx反向代理功能

Java+springboot实现nginx反向代理功能