spring cloud gateway网关处理跨域

本文介绍了在Spring Cloud Gateway中遇到的跨域问题,指出在Spring Boot 2.1.x以上版本存在的一个bug可能导致配置无效。提供了解决该问题的方法,即在Gateway中过滤掉部分配置,并给出了具体的配置类代码,通过这种方式成功解决了跨域请求的错误。
摘要由CSDN通过智能技术生成

首先,gateway中不能引入web的依赖:

在网上找到的跨域配置如下:

package com.wm.blog_gateway.config;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator;
import org.springframework.cloud.gateway.discovery.DiscoveryLocatorProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.ArrayList;


/**
 * 跨域处理,线上使用nginx替代
 */
@Configuration
public class CorsConfig implements GlobalFilter, Ordered {
    private static final String ALL = "*";
    private static final String MAX_AGE = "18000L";

    @Bean
    public RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient,
                                                                        DiscoveryLocatorProperties properties) {
        return new DiscoveryClientRouteDefinition
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
关于Spring Cloud Gateway的实战,有很多方面可以探索和实践。以下是一些常见的实战主题和示例: 1. 路由配置:使用Spring Cloud Gateway进行路由配置,将请求转发到不同的后端服务。可以通过YAML或Java代码方式进行配置,并可以使用各种条件和断言来实现动态路由。 2. 过滤器:利用Spring Cloud Gateway的过滤器功能,对请求进行预处理或后处理。常见的过滤器包括鉴权、请求转发修改、请求日志记录等。 3. 限流和熔断:使用Spring Cloud Gateway的限流和熔断功能,保护后端服务免受过载和故障的影响。可以使用内置的限流和熔断策略,或者集成第三方限流和熔断组件。 4. 请求重试:在网络不稳定的情况下,使用Spring Cloud Gateway的请求重试功能,自动重新发送请求,提高系统的可靠性和容错性。 5. 跨域支持:通过Spring Cloud Gateway配置跨域资源共享(CORS),允许跨域访问资源,提高前后端分离架构的灵活性。 6. 动态路由:结合服务注册中心(如Eureka或Consul)和配置中心(如Spring Cloud Config),实现动态路由的管理和配置。 7. 监控和日志:使用Spring Cloud Gateway的监控和日志功能,对请求进行统计和分析,了解系统的性能和健康状况。 以上只是一些常见的实战主题,实际上Spring Cloud Gateway还有更多功能和扩展性可供实践。你可以根据自己的需求和场景,选择适合的实战方向,深入学习和应用Spring Cloud Gateway
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值