Java SpringBoot接口,用于代理转发,隐藏真实接口
创始人
2025-06-01 09:58:12

背景

昨天来了一个活,客户需要远程发送指令给我们的一台服务器控制启动,但是我们并不想直接让他们访问以免暴露接口。这时候就提出来,我中转服务器封装一个接口,隐藏真实接口。简化如下:

假设客户端是A,我此时服务器是B,客户想要访问的是C。但是不能让他直接访问C,所以这时候就需要A ——> B——>C
此时我需要接收A的调用,然后将A传来的数据发送到C,然后最好再把C返回的结果返回给A,就大功告成。

推荐一个简单好用的工具

HTTP-Proxy-Servlet工具,比较成熟,github地址如下:
Smiley’s HTTP Proxy Servlet

下面讲一下我自己项目对它的使用情况。

前提

我的项目是基于 SpringBoot2.x的,故采用案例介绍的使用方式。

步骤

  1. 在pom.xml 添加依赖:
org.mitre.dsmiley.httpproxysmiley-http-proxy-servlet1.12.1

  1. 在你的项目配置目录下添加一个代理转发配置类如下:
package com.xxx.config;import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;import java.util.Properties;@Configuration
public class SolrProxyServletConfiguration implements EnvironmentAware {@Beanpublic ServletRegistrationBean servletRegistrationBean() {Properties properties= (Properties) bindResult.get();ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new ProxyServlet(), properties.getProperty("servlet_url"));servletRegistrationBean.addInitParameter(ProxyServlet.P_TARGET_URI, properties.getProperty("target_url"));servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, properties.getProperty("logging_enabled", "false"));return servletRegistrationBean;}private BindResult bindResult;@Overridepublic void setEnvironment(Environment environment) {Iterable sources = ConfigurationPropertySources.get(environment);Binder binder = new Binder(sources);BindResult bindResult = binder.bind("proxy.solr", Properties.class);this.bindResult = bindResult;}
}
  1. 在.yml配置文件添加 本服务api路径和目标服务器待转发地址:
proxy:solr:servlet_url: /solr/*    # 这里不能写ip地址,只写接口后半段即可target_url: http://solrserver:8983/solr   # 真实服务器接口地址

测试

1. 上传文件

postman访问本地服务地址,代理转发到另外一个服务器上,接口转发成功,且返回文件上传成功信息。

2. 上传json数据

通过。

总之,好用又简单,感兴趣的可以自己研究自己造轮子~

传送门

附上几个这方面的博主博客地址,有自己写的:

  1. spring boot转发HttpServletRequest到其他服务器,做到用户无感知接口代理转发
  2. SpringBoot 服务器实现接口代理转发,还可以对数据进行二次处理哦
  3. Java+springboot实现nginx反向代理功能
  4. github http-proxy-servlet工具

相关内容

热门资讯

2025最新消息“顶级娱乐开挂... 您好,顶级娱乐这款游戏可以开挂的,确实是有挂的,通过微信【8198015 】很多玩家在这款游戏中打牌...
2025最新消息“好运互娱开挂... 您好,好运互娱这款游戏可以开挂的,确实是有挂的,通过微信【8198015 】很多玩家在这款游戏中打牌...
2025最新消息“点我棋牌开挂... 您好:点我棋牌这款游戏可以开挂,确实是有挂的,需要了解添加微信【29290261很多玩家在这款游戏中...
2025最新消息“丫丫棋牌开挂... 亲,丫丫棋牌这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好,总...
游戏攻略心得体会文章攒劲甘肃麻... 您好!欢迎拜访本公司网站,咱们公司是专业研制及出售全国各地辅助软件1.亲,实际上攒劲甘肃麻将确实有挂...