Spring SpringBoot应用中实现反向代理服务器

1. 引入相关依赖

 <dependency>
     <groupId>org.mitre.dsmiley.httpproxy</groupId>
     <artifactId>smiley-http-proxy-servlet</artifactId>
     <version>1.7</version>
 </dependency>

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
 </dependency>

2. 配置相关代理设置

# 自定义代理相关配置
# 代理的本地路由
proxy.login_url: /login/*
proxy.update_url: /update/*
# 要代理的地址
proxt.target_url: http://www.baidu.com

3. 声明proxy的servlet,并对其进行配置即可:

注意:配置多个请求路径时需要设置不一样的名字

 registrationBean.setName("one");
 registrationBean.setName("two");

code:

package com.xiaoguai.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;
 
/**
 * @ClassName: SolrProxyServletConfiguration
 * @Description: 反向代理
 * @author: xiaoguai
 * @date: 2020年011月07日 12:11
 */
@Configuration
public class SolrProxyServletConfiguration {

    /**
     * 读取配置文件中路由设置
     * 修改
     */
    @Value("${proxy.update_url}")
    private String updateUrl;


    /**
     * 读取配置文件中路由设置
     * 登录
     */
    @Value("${proxy.login_url}")
    private String loginUrl;


    /**
     * 读取配置中代理目标地址
     */
    @Value("${proxy.target_url}")
    private String targetUrl;
 
    @Bean
    public Servlet createProxyServlet(){
        // 创建新的ProxyServlet
        return new ProxyServlet();
    }
 
    @Bean
    public ServletRegistrationBean proxyServletRegistration(){
        String url="/sessions_service/login?systemType=2&version=4.6.7";
        ServletRegistrationBean registrationBean= new ServletRegistrationBean(createProxyServlet(), updateUrl);
        //这个setName必须要设置,并且多个的时候,名字需要不一样
        registrationBean.setName("one");
        //设置网址以及参数
        Map<String, String> params = ImmutableMap.of(
                "targetUri", targetUrl,
                "log", "true");
        registrationBean.setInitParameters(params);
        return registrationBean;
    }

    @Bean
    public ServletRegistrationBean proxyServletRegistration2(){
        ServletRegistrationBean registrationBean= new ServletRegistrationBean(createProxyServlet(), loginUrl);
        //这个setName必须要设置,并且多个的时候,名字需要不一样
        registrationBean.setName("two");
        //设置网址以及参数
        Map<String, String> params = ImmutableMap.of(
                "targetUri", targetUrl,
                "log", "true");
        registrationBean.setInitParameters(params);
        return registrationBean;
    }
}

 

posted @ 2020-11-07 16:08  乖怪丶  阅读(3232)  评论(0编辑  收藏  举报
……