快捷搜索: 王者荣耀 脱发

SpringBoot使用ProxyServlet配置服务代理

SpringBoot使用ProxyServlet配置服务代理

实现代理服务功能,思路是:客户端发送请求,由代理服务端通过端口监听到请求,然后在作为代理去访问真实的服务器,最后由真实的服务器将响应返回给代理,代理再返回给浏览器。

引入相关依赖

<!-- https://mvnrepository.com/artifact/org.mitre.dsmiley.httpproxy/smiley-http-proxy-servlet -->
        <dependency>
            <groupId>org.mitre.dsmiley.httpproxy</groupId>
            <artifactId>smiley-http-proxy-servlet</artifactId>
            <version>1.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>

相关代理配置

# 自定义代理配置
# 代理的本地路由
proxy.servlet_url: /api/*
# 要代理的地址
proxy.target_url: http://www.baidu.com

代理配置类

package com.example.wellnessproxy.config;

import com.google.common.collect.ImmutableMap;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import java.util.Map;

/**
 * 实现代理配置
 *
 * @author zz
 * @since 2020/7/7
 */
@Configuration
public class ProxyServletConfiguration {
          
   

    // 读取配置文件中路由设置
    @Value("${proxy.servlet_url}")
    private String servletUrl;

    // 读取配置中代理目标地址
    @Value("${proxy.target_url}")
    private String targetUrl;

    @Bean
    public Servlet createProxyServlet() {
          
   
        // 创建新的ProxyServlet
        return new ProxyServlet();
    }

    @Bean
    public ServletRegistrationBean proxyServletRegistration() {
          
   
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(createProxyServlet(), servletUrl);
        //设置网址以及参数
        Map<String, String> params = ImmutableMap.of(
                "targetUri", targetUrl,
                "log", "true");
        registrationBean.setInitParameters(params);
        return registrationBean;
    }
}

测试效果

    访问本地请求,就可以访问到代理地址了
经验分享 程序员 微信小程序 职场和发展