說(shuō)明
針對(duì)前后端分離場(chǎng)景下的一種跨域方案初肉,如果不使用如nginx或者springboot的zuul網(wǎng)關(guān)等方案膝藕,可以采用 httpproxy 方案闹炉。
在需要對(duì)接接口的web服務(wù)加入以下配置:
- 需要引入的依賴:
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.10</version>
</dependency>
- 編寫配置方法類
@Configuration
public class ProxyServletConfiguration implements EnvironmentAware {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new ProxyServlet(), propertyResolver.getProperty("servlet_url"));
servletRegistrationBean.addInitParameter("targetUri", propertyResolver.getProperty("target_url"));
servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, propertyResolver.getProperty("logging_enabled", "false"));
return servletRegistrationBean;
}
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "proxy.solr.");
}
}
- 在application.yml中配置
server:
port: 8088
proxy:
solr:
servlet_url: /project/v1/*
target_url: http://localhost:8092/project/v1
配置說(shuō)明:
servlet_url : 對(duì)外可以訪問(wèn)的匹配路徑隘梨,如前端js 在web服務(wù)訪問(wèn)后端服務(wù)的一個(gè)接口氨淌,可以不加域名或者ip port;
target_url : 指向后端服務(wù)的根服務(wù)地址拼苍。
更多玖姑,請(qǐng)關(guān)注:
springboot 技術(shù)實(shí)踐總結(jié)