• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SpringBoot编写了网关

武飞扬头像
小龙哒
帮助1

设计

接口请求
文件请求
转发请求
客户端
A服务器 /api/xxxx Or /api/sys/file/downlaod
服务器 /xxxx

跨域三件套

AxiosCorsFilter

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AxiosCorsFilter extends CorsFilter {
    public AxiosCorsFilter() {
        super(configurationSource());
    }

    /**
     * 添加跨域
     *
     * @return
     */
    private static UrlBasedCorsConfigurationSource configurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);

        return source;
    }
}

学新通

ClassCorsConfig

@Configuration
public class ClassCorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration =new CorsConfiguration();
       corsConfiguration.addAllowedOrigin("*"); // 1
       corsConfiguration.addAllowedHeader("*"); // 2
       corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }
 
    @Bean
    public CorsFilter corsFilter() {
//        UrlBasedCorsConfigurationSource source= new UrlBasedCorsConfigurationSource();
//       source.registerCorsConfiguration("/**", buildConfig()); // 4
       final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
       final CorsConfiguration  config = new CorsConfiguration(); config.setAllowCredentials(true); 
 	  //允许cookies跨域 
 	  config.addAllowedOrigin("*");
 	 // 允许向该服务器提交请求的URI,*表示全部允许。。这里尽量限制来源域,比如http://xxxx:8080 ,以降低安全风险。。
 	  config.addAllowedHeader("*");
 	  // 允许访问的头信息,*表示全部 com.cxl.rc.smart.config.setMaxAge(18000L);
 	 
 	  //预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
 	  config.addAllowedMethod("*");
 	  //允许提交请求的方法,*表示全部允许,也可以单独设置GET、PUT等 com.cxl.rc.smart.config.addAllowedMethod("HEAD");
 	  config.addAllowedMethod("GET");
 	  // 允许Get的请求方法
 	  config.addAllowedMethod("PUT");
 	  config.addAllowedMethod("POST");
 	  config.addAllowedMethod("DELETE");
 	  config.addAllowedMethod("PATCH"); 
 	  source.registerCorsConfiguration("/**",config); 
 	  return new CorsFilter(source); 
        
    }
}
学新通

InterceptorConfig

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET,POST,PUT,DELETE,HEAD,OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(false).maxAge(3600);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        return converter;
    }

}
学新通

路由映射

public class RouterConfig {


    private static Map<String,String> config = new HashMap<>();

    static {
    	// key是匹配的前缀
        config.put("/api","http://你要跳转的ip:端口");
    }

    public static String match(String path) throws Exception{
        Set<String> strings = config.keySet();
        String s = null;
        for (String string : strings) {
            boolean equals = path.startsWith(string);
            if(equals){
                s = config.get(string);
            }
        }
        if(null == s){
            throw new Exception("["  path  "]没有找到指定路由");
        }
        return s;
    }

    public static String get(String path) throws Exception{
        Set<String> strings = config.keySet();
        for (String string : strings) {
            boolean equals = path.startsWith(string);
            if(equals){
                return string;
            }
        }
        throw new Exception("["  path  "]没有找到指定映射");
    }

}

学新通

接口实现

只是简单的实现而已,满足当前项目的需求。并没有做太多的完善,勿杠谢谢。

    @RequestMapping("**")
    public Object requests(@RequestBody(required = false) Map<String,Object> data, HttpServletRequest request, HttpServletResponse response) throws Exception{
        String path = request.getServletPath();
        String url = path.replaceFirst(RouterConfig.get(path), RouterConfig.match(path));

        if(request.getParameterMap().size() > 0){
            StringBuffer params = new StringBuffer(url   "?");
            Map<String, String[]> r = request.getParameterMap();
            for (String s : r.keySet()) {
                params.append(s "=" request.getParameter(s));
            }
            url = params.toString();
        }
        System.out.println("router >>>[" path "] >>>>> [" url "]");
        HttpRequest req = HttpUtil.createRequest(Method.valueOf(request.getMethod()), url);
        req.header("token",request.getHeader("token"));
        req.header("Content-Type",request.getHeader("Content-Type"));
        req.header("Accept",request.getHeader("Accept"));
        req.header("Host",request.getHeader("Host"));
        req.header("User-Agent",request.getHeader("User-Agent"));
        if(null != data) {
            req.body(JSONUtil.toJsonStr(data));
        }

        if(url.indexOf("download")>-1){
            response.getOutputStream().write(req.execute().bodyBytes());
            return "file download success~!";
        }else{
            return req.execute().body();
        }

    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeikca
系列文章
更多 icon
同类精品
更多 icon
继续加载