spring-cloud(十三)GateWay 跨域、HTTP 超时配置

spring-cloud(十三)GateWay 跨域、HTTP 超时配置


本文spring-cloud 版本为:hoxton.sr6

本文spring-boot版本为:2.2.x-2.3.x

在实际开发中,会涉及到跨域问题,请求时间超时设置等等,接下来,咱们就进行研究学习…

一、gateway 跨域问题解决

(1)java代码解决跨域问题

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
/**
 * @author lei
 * @version 1.0
 * @date 2020/10/21 21:18
 * @desc 代码设置 解决跨域
 */
@Configuration
public class GwCorsFilter {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
		// 允许cookies跨域
        config.setAllowCredentials(true); 
        // #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
        config.addAllowedOrigin("*");
        // #允许访问的头信息,*表示全部
        config.addAllowedHeader("*");
        // 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
        config.setMaxAge(18000L);
        //允许的方法 可设置* 即允许全部http请求方法类型
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

(2)yml配置解决跨域

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
          	# 允许向该服务器提交请求的URI
            allowedOrigins:
              - http://192.168.124.17
            # 允许跨域的方法
            allowedMethods:
              - GET
              - POST
              - DELETE
            # 预检请求的缓存时间(秒),即在这个时间段里对于相同的跨域请求不会再预检
            maxAge: 180

懒人版简写配置,一律写*

spring:
  application:
    #服务名配置
    name: app-gateway
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            #是否允许cookie跨域  true允许
            allowCredentials: true
            #允许跨域的url * 则允许全部
            allowedOrigins: '*'
            # 允许跨域的方法 * 则全部
            allowedMethods: '*'
            # 跨域预检时间
            maxAge: 180

二、HTTP超时时间设置

超时时间设置即响应和连接时间设置…

(1)对具体路由做http超时配置

spring:
  application:
    #服务名配置
    name: app-gateway
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            #是否允许cookie跨域  true允许
            allowCredentials: true
            #允许跨域的url * 则允许全部
            allowedOrigins:
              - http://192.168.124.17
            # 允许跨域的方法 * 则全部
            allowedMethods:
              - GET
              - POST
              - DELETE
            # 跨域预检时间
            maxAge: 180
#      default-filters:
#        - AddResponseHeader=X-Response-Default, panghu
#        - PrefixPath=/lei-app
      routes:
        #简单的路由
        - id: easy-order
          uri: http://localhost:9002/
          predicates:
            - Path=/order/**
        #根据服务名路由
        - id: server-order
          uri: lb://demo-order
          predicates:
            - Path=/order/**
          # 针对于当前路由的http超时时间设置
          metadata:
            response-timeout: 2000
            connect-timeout: 2000
        - id: server-product
          uri: lb://demo-product
          predicates:
            - Path=/lei-app/product/**,/zs/{aa}
          filters:
            - StripPrefix=1
     	 # 针对于当前路由的http超时时间设置
          metadata:
            response-timeout: 2000
            connect-timeout: 2000

因为我们得demo-product服务启动了两个,且有一个服务的接口线程睡眠了4秒,那么按照上方配置http 连接以及响应时间均为两秒的话,则有一个可正常访问,有一个服务则会报出异常

image-20201021214357794

image-20201021214417304

image-20201021214508873

如果对每个服务Http 超时设置不需要做那些细微的区别,我们则可以对整个服务群配置全局http超时:

(2)对全局路由超时

对我们所有的路由做一个全局的http连接 超时时间设置…

spring:
  application:
  cloud:
    gateway:
      httpclient:
        #默认为毫秒单位 connect-timeout 默认为45s
        connect-timeout: 1000
        #点进源码可设置不同单位,我这里设置为5s
        response-timeout: 5s

那么,问题来了,如果我的服务,即设置了全局http时间,又对某个别路由设置了特定的http设置,那么生效的是哪一个呢?咱们来测试一下…

假设,咱们现在的配置是这样

spring:
  cloud:
    gateway:
      httpclient:
        #默认为毫秒单位,connect-timeout 默认时长为45s
        connect-timeout: 5000
        #点进源码可设置不同单位,我这里设置为5s
        response-timeout: 5s
      routes:
        - id: server-product
          uri: lb://demo-product
          predicates:
            - Path=/lei-app/product/**,/zs/{aa}
          filters:
            - StripPrefix=1
          # 针对于当前路由的http超时时间设置
          metadata:
            response-timeout: 2000
            connect-timeout: 2000

image-20201021215916450

所以呢!!当我们针对某个路由的HTTP超时时间设置后以及又做了全局HTTP超时时间,其路由仍然是以自己路由超时时间设置为准!

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Cloud网关跨域配置可以通过以下步骤来完成。 首先,在Spring Cloud网关项目的配置文件中进行相关配置。可以通过在配置文件中设置以下属性来允许跨域访问: ```yml spring: cloud: gateway: globalcors: corsConfigurations: '[/**]': allowedOrigins: "*" allowedMethods: - GET - POST allowCredentials: true ``` 上述配置中,allowedOrigins设置为"*"表示允许来自所有域的请求。 其次,可以在编写路由规则的时候,设置cors参数来针对特定的请求路径进行跨域配置。例如: ```yml spring: cloud: gateway: routes: - id: service-route uri: http://localhost:8081 predicates: - Path=/service/** filters: - RewritePath=/service/(?<remaining>.*), /\$\{remaining} - RewritePath=/service/(?<remaining>.*), /\$\{remaining} metadata: response-headers: Access-Control-Allow-Origin: "*" Access-Control-Allow-Methods: "GET, POST" Access-Control-Max-Age: "3600" Access-Control-Allow-Headers: "Content-Type, x-requested-with, Authorization" ``` 在上述示例中,针对路径为/service/**的请求进行了跨域配置,允许来自任意域的请求,并设置了允许的请求方法和响应头信息。 最后,还可以使用自定义的CorsWebFilter来进行更灵活的跨域配置。可以通过编写一个实现CorsConfigurationSource接口的类,并在该类中自定义cors配置,然后在WebFluxConfigurer中注册该CorsConfigurationSource实现即可。 通过以上的配置和步骤,Spring Cloud网关可以实现跨域访问的配置。这样就能够允许不同域的请求访问网关,并实现前后端的数据交互。 ### 回答2: Spring Cloud Gateway 是基于Spring WebFlux框架的一个API网关服务,用于构建微服务架构中的路由转发和过滤器链。在Spring Cloud Gateway配置跨域请求是相对较简单的。 在Spring Cloud Gateway中可以通过添加过滤器来实现跨域请求。首先,在配置文件中添加路由配置,指定需要跨域的路径和目标服务。然后,编写一个全局的过滤器类,通过继承GlobalFilter和Ordered接口来实现全局过滤器。在过滤器中,通过CorsUtils类来判断请求是否为跨域请求,如果是,则设置跨域响应头信息。 具体的步骤如下: 1. 在application.yml文件中配置路由: ```yaml spring: cloud: gateway: routes: - id: myRoute uri: http://example.com predicates: - Path=/api/** filters: - StripPrefix=1 ``` 2. 创建一个全局的过滤器类CorsFilter.java: ```java @Component public class CorsFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); if (CorsUtils.isCorsRequest(request)) { ServerHttpResponse response = exchange.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } return chain.filter(exchange); } @Override public int getOrder() { return -1; } } ``` 3. 启动应用,并访问配置跨域接口。 通过以上步骤,我们可以简单地在Spring Cloud Gateway配置跨域请求。在过滤器中,我们判断请求是否为跨域请求,并在响应头中添加相关的跨域信息。这样,就能够实现对跨域请求的支持。 ### 回答3: Spring Cloud网关是一个基于Spring Cloud的微服务架构中的核心组件,它可以用来进行统一的请求路由、请求过滤、集中认证等功能。当我们在使用Spring Cloud网关时,可能会遇到跨域的问题,下面我将详细介绍Spring Cloud网关跨域配置。 要配置Spring Cloud网关跨域,我们可以在网关配置文件中添加如下代码段: ``` spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allowed-origins: '*' allowed-methods: - GET - POST - PUT - DELETE allowed-headers: '*' allow-credentials: true max-age: 1800 ``` 在这个配置中,我们使用`spring.cloud.gateway.globalcors.cors-configurations`参数指定了全局的CORS配置。`'[/**]'`表示匹配所有路径,我们也可以根据自己的需求指定一个具体的路径。`allowed-origins`指定了允许的源,可以使用`*`表示允许所有源。`allowed-methods`指定了允许的HTTP方法。`allowed-headers`指定了允许的自定义头信息。`allow-credentials`表示是否允许发送cookie等身份验证信息。`max-age`表示预检请求的缓存时间。 除了全局配置外,我们还可以在GatewayFilter中对特定的路径进行跨域配置,例如: ``` @Configuration public class GatewayConfig { @Bean public RouteLocator routeLocator(RouteLocatorBuilder builder) { return builder.routes() .route(r -> r.path("/api/**") .filters(f -> f.hystrix(c -> c.setFallbackUri("/fallback"))) .uri("lb://service-a")) .build(); } @Bean public CorsWebFilter corsFilter() { return new CorsWebFilter(new UrlBasedCorsConfigurationSource()); } } ``` 在上述配置中,`routeLocator()`方法用于配置路由规则,其中`.path("/api/**")`表示匹配以`/api/`开头的路径,然后使用`filters()`方法添加一些过滤器,最后使用`uri()`方法将请求转发到service-a服务。 `corsFilter()`方法用于添加CorsWebFilter,通过`UrlBasedCorsConfigurationSource`来实现对特定路径的跨域配置。 以上就是Spring Cloud网关跨域配置的一些常用方法,我们可以根据实际需求选择适合的方式来配置跨域
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值