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>


 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用 Spring Boot 实现一个 Nginx 反向代理的类: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class ReverseProxyApplication { public static void main(String[] args) { SpringApplication.run(ReverseProxyApplication.class, args); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` 这个类使用Spring Boot 框架,其中包含了一个 `RestTemplate` 的 Bean,用于发送 HTTP 请求。在实际使用中,我们可以通过注入 `RestTemplate` 来发送请求。 接下来,我们需要编写一个 Controller 类,用于接收请求并将其转发到目标服务器: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class ReverseProxyController { @Autowired private RestTemplate restTemplate; @GetMapping("/{path}") public ResponseEntity<String> proxy(@PathVariable String path) { String url = "http://example.com/" + path; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); return response; } } ``` 这个 Controller 类中包含了一个 `RestTemplate` 的实例,用于发送 HTTP 请求。在 `proxy` 方法中,我们将请求路径拼接到目标服务器的 URL 上,并使用 `RestTemplate` 发送 GET 请求。最后,我们将目标服务器的响应返回给客户端。 以上就是使用 Spring Boot 实现一个 Nginx 反向代理的类的全部内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值