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>

 

  • 4
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 26
    评论
Spring Boot中可以通过组合使用代理服务器和HTTP请求转发实现代理转发。具体步骤如下: 1. 配置代理服务器 在application.properties文件中配置代理服务器的地址和端口号: ``` # 配置代理服务器地址和端口号 spring.proxies.host=proxy.example.com spring.proxies.port=8080 ``` 2. 创建RestTemplate对象 在创建RestTemplate对象时,需要设置代理服务器的地址和端口号: ```java @Configuration public class RestTemplateConfiguration { @Value("${spring.proxies.host}") private String proxyHost; @Value("${spring.proxies.port}") private int proxyPort; @Bean public RestTemplate restTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); requestFactory.setProxy(proxy); return new RestTemplate(requestFactory); } } ``` 3. 创建转发服务 创建一个转发服务,用于将HTTP请求转发到目标服务: ```java @RestController public class ForwardController { private final RestTemplate restTemplate; public ForwardController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/forward") public String forward(HttpServletRequest request) { // 获取目标URL String url = request.getParameter("url"); // 发送HTTP请求获取响应 ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); // 返回响应 return responseEntity.getBody(); } } ``` 4. 创建代理服务 创建一个代理服务,用于接收HTTP请求并将请求转发转发服务: ```java @RestController public class ProxyController { private final RestTemplate restTemplate; public ProxyController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/proxy") public String proxy(HttpServletRequest request) { // 获取转发URL String url = request.getParameter("url"); // 构造转发URL String forwardUrl = "http://localhost:8080/forward?url=" + url; // 发送HTTP请求获取响应 ResponseEntity<String> responseEntity = restTemplate.getForEntity(forwardUrl, String.class); // 返回响应 return responseEntity.getBody(); } } ``` 5. 配置路由规则 在application.properties文件中配置路由规则: ``` # 配置路由规则 spring.cloud.gateway.routes[0].id=proxy spring.cloud.gateway.routes[0].uri=http://localhost:8081 spring.cloud.gateway.routes[0].predicates[0]=Path=/proxy/** ``` 6. 启动服务 启动代理服务和转发服务,访问代理服务的URL即可实现代理转发。 以上就是使用Spring Boot实现代理转发的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张音乐

请我喝杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值