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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM